mintbox mintbox - 1 month ago 4
C++ Question

why does while loop using cin.get() function outputs result twice?

#include <iostream>
using namespace std;

int main()

int a ;
while ( ( a = cin.get() ) != EOF )

cout << "hi" <<endl;

} // end while


I wonder why this outputs "hi" twice whenever I input once.

for example

input : 1
output : hi


Your input actually consists of two characters: the character 1 followed by a newline.

Try piping in the contents of a file that only contains one byte, or a one-letter string without newline, and you'll see only one "hi".