Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using scanf in a while loop

Probably an extremely simple answer to this extremely simple question:

I'm reading "C Primer Plus" by Pratta and he keeps using the example

while (scanf("%d", &num) == 1)...

Is the == 1 really necessary? It seems like one could just write:

while (scanf("%d", &num))

It seems like the equality test is unnecessary since scanf returns the number of objects read and 1 would make the while loop true. Is the reason to make sure that the number of elements read is exactly 1 or is this totally superfluous?

like image 478
Tyler Brock Avatar asked Jun 04 '10 01:06

Tyler Brock


People also ask

Can you use scanf in a while loop?

scanf() function returns number of items it successfully reads. Since in your case it is reading one number n , scanf() returns 1. When you give a input file for the code to run, it returns 0 on reaching end of the file (EOF).

Why scanf is not working in loop in C?

That is because there is a left over newline character in the input buffer.

Can we use scanf in if condition?

Try to compile this program and run it, and you will see you can use scanf() inside an if, else or else if clause.

Can we use scanf in strings?

You can use the scanf() function to read a string. The scanf() function reads the sequence of characters until it encounters whitespace (space, newline, tab, etc.).


1 Answers

In C, 0 is evaluated to false and everything else to true. Thus, if scanf returned EOF, which is a negative value, the loop would evaluate to true, which is not what you'd want.

like image 108
JRL Avatar answered Oct 14 '22 16:10

JRL