Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the return value of "scanf()" to check for end of file

Tags:

c

file

scanf

I was searching the net on how to use return value of scanf to check the end of file! I found the following code.But i am having difficulty in understanding?

How is this method working?

What does the '~' operator signify?

while(~scanf("%d",&n)) { 
  /* Your solution */
}
like image 459
poorvank Avatar asked Dec 20 '22 06:12

poorvank


2 Answers

This is a horrible way to check if a value is different from -1. ~x returns the bitwise negation of x. So having in mind the complimentary code used for negative numbers(on most compilers by the way so this approach is not even very portable) -1 is represented by a sequence of 1-s and thus ~(-1) will produce a zero.

Please don't use this approach. Simply write scanf("%d", &n) != EOF Way easier to understand.

like image 57
Ivaylo Strandjev Avatar answered Dec 29 '22 11:12

Ivaylo Strandjev


~ is the bitwise NOT operator. This is therefore a slightly obfuscated way of looping until scanf returns something other than -1. In other words,

while(~scanf("%d",&n))

is equivalent to

while(scanf("%d",&n) != -1)
like image 29
simonc Avatar answered Dec 29 '22 10:12

simonc