1

編集: getchar(); を追加する必要がありました。scanf("%i", &choice); の後 今では一度だけ尋ねます!

どうやら、2回出力する原因となっているケーススイッチです。ケーススイッチの外で関数を呼び出すと1が出力されますが、スイッチ内で呼び出すと2回出力されます

これは何が原因ですか?私はscanfの選択を疑いますか?

    #include <stdio.h>
        #include <stdlib.h>
        #include <string.h>

        void test();
        void choose();
        int main(void)
        {   
//if i call here its fine
            test();
            choose();
            return 0; 
        }

        void choose()
        {
            int choice;

            do
            {
                printf("1 - Testing if double ask\n");
                printf("2 - Exit\n");
                printf("Please enter your choice: ");       
                scanf("%i", &choice);

                switch(choice)
                {//but pressing 1 here asks twice?
                    case 1:         
                        test();
                        break;
                    default:
                        if(choice !=2)
                            printf("Input Not Recognized!\n");
                        break;          
                }
            }
            while(choice !=2);
            if(choice == 2)
                printf("Ciao!");
        }
        void test()
        {
printf("HELLO");
                char *name = malloc (256);

                do      
                {
                    printf("Would you like to continue (y/n)\n");
                    fgets(name, 256, stdin);
                }
                while(strncmp(name, "n", 1) != 0);
                free (name);
        }
4

2 に答える 2

4

まず、C 文字列を比較演算子!=and と比較することはできません==。これには を使用する必要がありますstrcmp

do { ... } whileさらに、この場合、ループがより便利であることがわかると思います。nameユーザーが入力を追加する前に、一度チェックしています。

次に注意することはfgets、入力に改行が保持されることです。そのため、strcmp.

于 2012-08-23T01:45:03.270 に答える
1

文字列の比較は C のようには機能しません。string.h で strcmp を使用する必要があります。

あるいは、名前の最初の文字を見ることもできます。

while(name[0] != 'n')
于 2012-08-23T01:43:59.857 に答える