Why is scanf stuck inside a while loop?

I used 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, printf() does not display this number unless I enter another number. Why?

+4
source share
4 answers

\n in your scanf format is interpreted as "any number of spaces". It keeps reading spaces (spaces, tabs, or carriage returns) until it hits something that is not a space.

+5
source

You get this behavior because of the tail \n in the input format. He searches for empty space and does not know when he has finished scanning a space until he meets a non-white space. Do not put a trailing space in scanf() -family format lines unless you really know what you are doing or are really dealing with user input (input comes from a program or file or line).

Note that your code should check the return value from scanf() ; it will go completely into an infinite loop if it encounters an EOF (or, indeed, if it encounters a non-numeric, non-white space). In addition, when specifying such a new line, one number per input line is not applied. The user can have fun typing 1 2 3 4 5 6 7 8 9 0 on one line, and your code will cycle through the cycle evenly 9 times before getting stuck.

You can also avoid problems using fgets() (or POSIX getline() ) to read the input line, and then use sscanf() to convert the read data to a number. Note that the resulting newline is harmless.

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

I usually just follow

 scanf("%d", &input); 

without "\ n"

+1
source

If you look at the scanf link, you will see that:

The format string consists of space characters (any single space character in the format string consumes all available consecutive space characters from input)

Thus, \n will cause this effect if you do not want this behavior to just leave \n :

 scanf("%d", &input); 
+1
source

Source: https://habr.com/ru/post/1490195/


All Articles