3

以下は私のコードのスニペットです。fscanfの代わりに使用する方が良いことを学びましたscanf。しかし、 fscanf は入力を待っていません

switch (argc) {
            case 2: printf("\nEnter the subject code: ");
                while(fgets(temp_op->subject, BUF_NOTES, stdin)==NULL);
            case 3: printf("\nEnter the topic: ");
                while(fgets(temp_op->topic, BUF_TOPIC, stdin)==NULL);
            case 4: printf("\nEnter the Level: ");
                flag = fscanf(stdin,"%d",&temp_op->level);
            case 5: printf("\nEnter the Answer Key: ");
                while(fgets(temp_op->key, BUF_KEY, stdin)==NULL);
            case 6: printf("\nEnter any additional notes(optional): ");
                while(fgets(temp_op->notes, BUF_NOTES, stdin)==NULL);
                break;
            default:printf("\nExcess Arguments");
        }

問題は ですcase 5。fgets は入力を待っていませんが、ケース 6 はうまくいっています。

case 4ただし、 「flag =...」という行をコメントアウトすると、次の fgets で入力を求めるプロンプトが表示されます。奇妙な。以前の fscanf が後の fgets に影響を与えるのはなぜだろうか。私の構造定義は次のとおりです。

typedef struct {
int mode ;
int level;
char subject[BUF_SUBJECT], topic[BUF_TOPIC], notes[BUF_NOTES], key[BUF_KEY];
} operation;

完全なソースはhttp://pastebin.com/HVvGC3B7にあります

何が間違っている可能性がありますか?

4

2 に答える 2

5

あなたは混合scanf()していますfgets()- 避けるのが最善です。

fscanf(stdin,"%d",...\nを入力キューに残し、fgets()追加の入力を待たずに次の処理で消費します。

fgets()thoguhout を使用sscanf(buffer, "%d", ...し、整数を取得するために使用することをお勧めします。

于 2013-10-09T18:13:02.633 に答える
2
             case 4: printf("\nEnter the Level: ");
                flag = fscanf(stdin,"%d",&temp_op->level);
                //Here Return key left in buffer
             case 5: printf("\nEnter the Answer Key: ");
                while(fgets(temp_op->key, BUF_KEY, stdin)==NULL); // escapes because of newline 

getchar();回避するには、単に前に追加しcase 5ます。

またはchuxが提案したように、使用することもできますsscanf()

于 2013-10-09T18:19:29.193 に答える