[英]c: reading input with while(scanf()==1) isn't leaving the loop
I'm reading from stdin into an array input[], but it never leaves the loop after reading the input and keeps expecting more input. 我正在从stdin读入数组input [],但在读完输入之后再也不会离开循环,并且一直期待着更多的输入。 What am I doing wrong?
我究竟做错了什么?
char input[1000];
while(scanf("%s",input)==1){
printf("%s\n",input);
}
What you expect, how do you try to terminate it? 您期望什么,如何尝试终止它?
scanf("%s", input)
keeps waiting input always and always returns 1 if stdin
is life, it skips whitespaces and matches the first char sequence without whitespaces. scanf("%s", input)
始终保持输入等待状态,如果stdin
是life,则始终返回1,它会跳过空格并匹配没有空格的第一个char序列。 Please read the manual carefully. 请仔细阅读本手册。
If you want to continue scanf
using then you should provide a special string for breaking the loop. 如果要继续使用
scanf
,则应提供一个特殊的字符串来中断循环。
Since scanf()
returns **the number of elements successfully read, you must find a way to make it fail to read the %s
. 由于
scanf()
返回**成功读取的元素数,因此您必须找到一种使它无法读取%s
。 One common practice is to end the input with EOF, which is Ctrl-Z
then Enter
in Windows console, and Ctrl-D
on a Unix terminal. 一种常见的做法是以EOF结束输入,即在Windows控制台中
Ctrl-Z
然后Enter
,在Unix终端上Ctrl-D
。 After reading EOF scanf()
will return EOF
which is of course not 1, then the loop exits normally. 读取EOF之后,
scanf()
将返回EOF
,该EOF
当然不是1,然后循环正常退出。
Alternatively, you can use a custom terminating string in your code: 另外,您可以在代码中使用自定义终止字符串:
char input[1000];
while (scanf("%s", input) == 1) {
if (strcmp(input, "end") == 0) {
// End the loop
break;
}
printf("%s\n", input);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.