Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is scanf stuck inside a while loop?

Tags:

c

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?

like image 233
user1701840 Avatar asked Jan 12 '23 23:01

user1701840


2 Answers

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.

like image 80
Vaughn Cato Avatar answered Jan 17 '23 17:01

Vaughn Cato


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.

like image 26
Jonathan Leffler Avatar answered Jan 17 '23 15:01

Jonathan Leffler