What is the difference in behavior between cin and getchar?

While working on a problem on UVa Online Judge, I received “Accepted” for my program which started like so:

int main() {
    int i, j;
    while(cin >> i >> j) {

However, when I replaced that with this:

void read(int &n) {
    n = 0;
    int sign = 1;
    char c = getchar_unlocked();
    while(c<'0' || c>'9') {
        if(c == '-') sign = -1;
        c = getchar_unlocked();
    }
    while(c>='0' && c<='9') {
        n = n*10+c-'0';
        c = getchar_unlocked();
    }
    n*=sign;
}
int main() {
    int i, j;
    while(1) {
        read(i); read(j);

I get TLE. The function read() is something I found here on codechef, and I believe it is used by many for fast input. However since I am new to C++ I have simply copied it without understanding the difference between cin and getchar_unlocked. I also do not understand how UVa inputs to my program. I know that my second piece of code contains an infinite loop, but it seems that the first example also loops indefinitely, so I assumed that UVa did not care. What is the difference?

There is a big difference between the two loops.
In the first one, you use cin, which will return a null pointer if there are no more values in the file.
The second while will run forever since “1” will always be true, no matter what you have in the file. get_char will not cause the program to stop, even if all the characters from the file are “consumed”.

For “cin” read this: http://stackoverflow.com/questions/6791520/if-cin-x-why-can-you-use-that-condition

1 Like

This makes sense! Thank you for your explanation. So what does UVa send to my program to terminate it? Is it a random invalid character, some special character, or something else entirely?

AFAIK your first piece of code does not run indefinitely. If I am getting this right, the problem you are solving has an input format such that it requires even number of integers. So “while (cin >> i >> j)” will execute until the integers are provided by UVa, while your second piece of code will run even if there is no input from the online judge (ie, after all integers have been provided).