I’m just getting started with Codechef and just solved the TEST problem. While my solution was accepted, I looked for answers submitted by top coders. In the solution submitted by @victoralin10, there’s the following line:
while( scanf("%d",&n) == 1 and n != 42 )printf("%d\n",n);
I understand why n!=42 has been used, but what is the significance of scanf("%d",&n) == 1
?
Thanks
Scanf returns the number of values successfully inputted. scanf("%d",&n) ==1
means that there was an n, and we have not reached the end of the file.
3 Likes
The given code is:
while(1 == scanf("%d", &n) && n != 42) {
printf("%d\n", n);
}
So you have a problem understanding the logical expression i.e. 1 == scanf("%d", &n) && n != 42
.
-
scanf()
high-level I/O function in C/C++ which returns an integer value == the number of input read from the STDIN stream, and it returns -1 when some error occurs while reading the data from STDIN or when EOF condition is matched.
Refer to scanf() Documentation.
-
Also, pay attention to the way expression is written i.e. first the value is read using scanf()
and then it is checking n != 42
or not.