fscanf for stdin不提示输入

fscanf for stdin不提示输入,c,pointers,struct,fgets,scanf,C,Pointers,Struct,Fgets,Scanf,下面是我的代码片段。我学会了使用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: ");

下面是我的代码片段。我学会了使用
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做得很好

但是,如果我注释掉
案例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;
完整资料来源于

可能有什么问题?

您将
scanf()
fgets()
混合使用-最好避免

fscanf(stdin,“%d”…
\n
留在输入队列中,以下
fgets()
在不等待其他输入的情况下使用该队列

建议使用
fgets()
thoguhout并使用
sscanf(缓冲区,“%d”…
获取整数

             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 
为了避免在案例5之前添加
getchar();


或者按照chux的建议,您也可以使用
sscanf()

fscanf是否将换行符保留在缓冲区中?尝试
fflush()
强制输出缓冲区发出,这通常发生在
\n
上。顺便说一句,您忘记了开关
fscanf()中的
中断;
可能没有消耗所有的输入,因此
fgets()
找到了一些缓冲字符,不需要等待用户的额外输入。@Grijesh Chauhan我认为OP故意省略了
中断
。在我的编码手册中,任何时候
案例
“都会进入下一行代码(这不是
break
),必须包含一个特定的注释。可能简单到
//通过
@Jay Aurabind BTW:看起来像一个无限循环
,而(fgets(…,…,stdin)==NULL)
您是否应该得到EOF或I/O错误。但是当我需要使用sscanf从stdin接收时,我应该用什么来代替
缓冲区
?stdin产生警告,并且也不工作,因为缓冲区应该是手册中提到的
常量字符*
。仅
getchar()
似乎在处理无限循环,反之亦然!:P如果我不把NULL放在那里,我会得到循环:)@Jay Aurabind,人们不会直接使用
sscanf()
来读取
stdin
。读取缓冲区而不是扫描缓冲区:
字符缓冲区[sizeof(int)*3+3];if(fgets(buffer,sizeof buffer,stdin)==NULL)handle_EOR_或_error_IO();如果(1!=sscanf(buffer,%d,&temp\u op->level)handle_format_error();
我想您误解了
sscanf(const char*,
常量的用法。提供给
sscanf()的缓冲区参数
可以是类型
char*
const char*
const
意味着
sscanf()
不会试图通过
buffer
更改指向的数据指针。这并不是说
const char*
必须提供给
anfssc()