Curious Curious - 1 year ago 70
C++ Question

Reading till new line in C++ goes in an infinite loop

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)


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
fetched as


doesn't seem to help resolve the issue here

Ben Ben
Answer Source

If you get an error on std::cin (which is of type std::istream), then you need to clear it:

int integer;
cin >> integer;
if (!cin) {
    cin.clear(); // If an error occurred, we need to clear it!

Then it will work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download