简体   繁体   English

为什么scanf卡在while循环中?

[英]Why is scanf stuck inside a while loop?

I used a scanf() inside a while loop. 我在while循环中使用了scanf()。

while(1)
{
    int input = 0;
    scanf("%d\n", &input);
    printf("%d\n", input);
}

When I run this program, and I enter a number, the printf() is not displaying that number unless I enter another number again. 当我运行这个程序,并输入一个数字时, printf()不会显示该数字,除非我再次输入另一个数字。 Why? 为什么?

The \\n in your scanf format is interpreted as "any amount of whitespace". scanf格式的\\n被解释为“任意数量的空格”。 It keeps reading whitespace (spaces, tabs, or carriage returns) until it hits something that isn't whitespace. 它一直在读取空格(空格,制表符或回车符),直到它碰到不是空格的东西。

You get that behaviour because of the trailing \\n in the input format. 由于输入格式中的尾随\\n ,您会得到该行为。 That looks for white space, and doesn't know when it has finished scanning white space until it comes across a non-white space character. 它寻找空白区域,并且不知道它何时完成扫描空白区域,直到它遇到非白色空格字符。 Don't put trailing white space in your scanf() -family format strings unless you really know what you're doing or you aren't actually dealing with user input (the input comes from a program or file or string). 不要在scanf()家庭格式字符串中放置尾随空格,除非你真的知道你正在做什么或者你实际上没有处理用户输入(输入来自程序或文件或字符串)。

Note that your code should be checking the return value from scanf() ; 请注意,您的代码应该检查scanf()的返回值; it will go into an infinite loop fully if it encounters EOF (or, indeed, if it encounters a non-numeric, non-white space character). 如果它遇到EOF(或者,如果它遇到非数字,非白色空格字符),它将完全进入无限循环。 Also, specifying the newline like that does not enforce one number per input line. 此外,指定这样的换行不会强制每个输入行一个数字。 The user might merrily type 1 2 3 4 5 6 7 8 9 0 on a single line, and your code will equally merrily cycle 9 times around the loop before getting stuck. 用户可以在一行中快乐地键入1 2 3 4 5 6 7 8 9 0 ,并且您的代码在被卡住之前将同样快速循环9次循环。

You can also evade the problems by using fgets() (or POSIX getline() ) to read a line of input and then use sscanf() to convert the read data into a number. 您还可以通过使用fgets() (或POSIX getline() )读取输入行,然后使用sscanf()将读取的数据转换为数字来规避问题。 Note that the trailing newline is then harmless. 请注意,尾随换行符是无害的。

scanf("%d\n", &input);

I usually just go with the follow 我通常只是跟随

scanf("%d", &input);

without the "\\n" 没有“\\ n”

If you look at a reference for scanf you will see that: 如果你查看scanf的参考,你会看到:

The format string consists of whitespace characters (any single whitespace character in the format string consumes all available consecutive whitespace characters from the input) 格式字符串由空格字符组成(格式字符串中的任何单个空格字符都使用输入中的所有可用连续空白字符)

So the \\n will trigger this effect, if you don't want this behavior just leave out the \\n : 所以\\n会触发这种效果,如果你不希望这种行为只是遗漏了\\n

scanf("%d", &input);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM