Welcome to MSDN Blogs Sign in | Join | Help

scanf() vs cin

It has been a while since the last time I wrote some C code, since I come from a C++ background, hence I seldom use scanf(). Without going into many details for the reasons why one should use scanf or cin, I just want to point out one difference on return values. When should I stop the loop, here’s an example:

The input looks like this:

1 10
100 200
201 210
900 1000

in C++, using cin, you can stop the loop when cin returns 0:

int i, j;

while (cin >> i >> j) {
    doSomething(i, j);
}

I re-wrote my C++ code in C like this:

int i, j;

while (scanf("%i %i", &i, &j)) {
    doSomething(i, j);
}

Because my memory didn’t come to the rescue and because I’m used to cin, I expected the loop to stop in the same way. I was wrong, I forgot that scanf will return –1 when it reaches EOF. Here’s the correct code:

int i, j;

while (scanf("%i %i", &i, &j) != EOF) {
    doSomething(i, j);
}
Published Sunday, March 29, 2009 10:59 AM by mohamedg
Filed under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# infoblog » scanf() vs cin

Sunday, March 29, 2009 11:17 AM by infoblog » scanf() vs cin

Leave a Comment

(required) 
required 
(required) 

  
Enter Code Here: Required
 
Page view tracker