Freigeben über


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);
}

Comments