scanf 不读取输入
我阅读了更多有关 scanf 的线程,发现一些答案没有帮助我:
while(!comanda){
int tmp;
if (scanf("%d", &tmp) == 0)
getchar();
else{
comanda = tmp;
fprintf(stdout,"%d",&comanda);
fflush(stdout);}
}
}
问题是执行这行代码后,什么也没有发生。之后我检查了“comanda”,但它不执行。
I read more threads about scanf and I found some answers bot none helped me:
while(!comanda){
int tmp;
if (scanf("%d", &tmp) == 0)
getchar();
else{
comanda = tmp;
fprintf(stdout,"%d",&comanda);
fflush(stdout);}
}
}
The problem is that after this lines of code get executed, nothing happens. After this I have a check on "comanda" which does not execute.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
scanf
和所有格式化输入函数的问题之一是终端往往在行模式或熟模式,API 专为原始模式设计。换句话说,scanf
实现通常在遇到换行符之前不会返回。输入被缓冲,以后对scanf
的调用将消耗缓冲的行。考虑以下简单的程序:您可以在按返回之前输入多个数字。这是运行该程序的示例。
每次调用
scanf
都会从输入流中读取一个数字,但第一次调用直到我按下 return 后才返回。其余的调用立即返回,不会阻塞更多输入,因为输入流已被缓冲,并且它可以从流中读取另一个整数。替代方法是使用
fgets
并一次处理整行数据或使用 终端界面禁用 “规范输入处理”。大多数人使用fgets
因为 POSIX 的终端接口部分没有在 Windows 下实现。One of the problems with
scanf
and all of the formatted input functions is that terminals tend to operate in line mode or cooked mode and the API is designed for raw mode. In other words,scanf
implementations generally will not return until a line feed is encountered. The input is buffered and future calls toscanf
will consume the buffered line. Consider the following simple program:You can enter multiple numbers before pressing return. Here is an example of running this program.
Each call to
scanf
read a single number from the input stream but the first call did not return until after I pressed return. The remaining calls returned immediately without blocking for more input because the input stream was buffered and it could read another integer from the stream.The alternatives to this are to use
fgets
and processing entire lines of data at one time or using the terminal interface to disable "canonical input processing". Most people usefgets
since the terminal interface section of POSIX is not implemented under Windows.如果您的
scanf("%d", &tmp)
可以返回 3 个值之一1
这意味着一个值被读取并放置在 tmp 中,getchar()
检测并消除该字符),EOF
表示 stdin 处于文件结束状态。无论您执行多少次 getchar() ,“文件结束”条件都不会消失,您将陷入无限循环。还要测试 scanf 的返回值是否为 EOF。
或者,甚至更好,重做您的程序,使用
fgets()
读取整行,并使用sscanf()
解析它。Your
scanf("%d", &tmp)
can return one of 3 values1
it means a value was read and placed in tmp0
it means there was a bad character in buffer (which you detect and get rid of with the nextgetchar()
)EOF
it meansstdin
is at end-of-file condition. No matter how manygetchar()
s you do, the 'end-of-file' condition is not going away and you're stuck in an infinite loop.Also test the return value from scanf for EOF.
Or, even better, redo your program to read a full line with
fgets()
and parse it withsscanf()
.