Given the following program
#include <iostream>
#include <string>
using namespace std;
int main() {
int integer;
cin >> integer;
if (!cin) {
string str;
char ch;
while ((ch = cin.get()) != '\n') {
cout << "scanning" << endl;
cout << "got " << static_cast<int>(ch) << endl;
}
}
return 0;
}
When given this input file (redirected input)
x123
With a newline at the end, why does the program go into an infinite loop? Shouldn't it stop after encountering the newline at the end of the file? I keep getting the value of ch
fetched as -1
..
Thanks!
Note cin.ignore()
doesn't seem to help resolve the issue here