Search code examples
c++linuxstdout

Code not working as expected in Linux g++?


In linux g++ compiler, the third number is not printed, and "reached" is not printed. But I expected that "reached" will be printed, after that it would go into infinite loop. It executes as expected on windows using Codeblocks

#include <iostream>
int main()
{
    int a;
    for (int i = 0; i < 3; i++) {
        std::cin >> a;
        std::cout << a;
    }
    std::cout << "reached";
    while (1) {}
    return 0;
}

Solution

  • Because you are never ending the program, and thus never flushing your stdout (cout) output.

    You can either change:

     cout<<"reached";
    

    to:

     cout<<"reached" << endl;
    

    or:

     cout<<"reached" << flush;
    

    Or simply remove your forever loop.

    Another alternative is to use cerr << "reached"; - that will be printed immediately, since cerr is not buffered.