简体   繁体   中英

Why is scanf stuck inside a while loop?

I used a scanf() inside a while loop.

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. Why?

The \\n in your scanf format is interpreted as "any amount of whitespace". 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. 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).

Note that your code should be checking the return value from 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). 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.

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. 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"

If you look at a reference for scanf you will see that:

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 :

scanf("%d", &input);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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