下面给出了我的代码片段。我了解到最好使用 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");
}
问题是针对案例 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
有什么问题吗?
最佳答案
您正在将 scanf()
与 fgets()
混合使用 - 最好避免。
fscanf(stdin,"%d",...
将 \n
留在输入队列中,以下 fgets()
无需等待额外输入即可使用。
推荐使用 fgets()
thoguhout 并使用 sscanf(buffer, "%d", ...
获取整数。
关于c - stdin 的 fscanf 不提示输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19279474/