Small scanf input tips till EOF


while(~scanf("%d %d", &a, &b))


In many problems we need to take input till EOF (End of File).

If we take input in c++ with scanf we can check if the return value of scanf is equal to -1 or equal to the number of input variables. Ok enough talk, we do one of the following most of the time

while(scanf("%d %d", &a, &b) == 2)


while(scanf("%d %d", &a, &b) != -1) //EOF == -1

Now we know that -1 means all 111111….1 in binary. So if we NOT -1 we get 0000000..0000 in binary which C/C++ detects as false.

So we can basically change

while(someValue != -1)



So we can write

while(~scanf("%d %d", &a, &b))

Thanks to yooo‘s code from codeforces

2 responses to “Small scanf input tips till EOF

  1. Pingback: Small Tips& Trics for Competitive Programming Contests | Enzam's Blog

Want to share your views? Please do reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s