【发布时间】:2013-10-09 18:07:40
【问题描述】:
下面给出的是我的代码中的一个 sn-p。我学会了使用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 =...”,那么下一个 fget 将提示输入。奇怪。我想知道为什么以前的 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
可能出了什么问题?
【问题讨论】:
-
fscanf是否将换行符留在缓冲区中? -
尝试
fflush()强制输出缓冲区发射,这通常发生在\n。 -
顺便说一句,你在 switch 中忘记了
break; -
fscanf()可能没有消耗所有输入,因此fgets()找到了一些缓冲字符,不需要等待用户的额外输入。 -
@Grijesh Chauhan 我认为 OP 故意省略了
break。在我的编码手册中,任何时候case"drop through` 到下一行代码(即不是break),都必须包含 特定 注释。也许就像// drop through一样简单.
标签: c pointers struct fgets scanf