problem with cin

code::

#include <iostream>

using namespace std;

int main()
{
    char c;
    cin >> c;
    while(c != '\n') {
        cin >> c;
    }

return 0;
}

Why it’s not terminate when we press enter(\n)
although it’s work when i use getchar() to read a char but what’s problem with cin?

it does not work the way you think. std::cin is actually buffered.

anything trying to read from it is blocked until it is explicitely flushed.

(that’s the very reason why this “function” can decode an integer from a stream of pure characters)

the buffer is either flushed when it’s full, or when it encounters a specified character (’\n’ by default).

with your program :

#include <iostream>
using namespace std;
int main()
{
    char c;
    cin >> c;

    // here, we do not enter the while loop until '\n' is pressed.
    // when it is, it is discarded, and then every character is
    // "popped out" from the stream, and compared with '\n', which
    // actually never occurs. thus you never exit the loop.

    while(c != '\n') {
        cin >> c;
    }
return 0;
}

http://www.cplusplus.com/reference/iostream/istream/

2 Likes
//