1

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

SergV
  • 1,269
  • 8
  • 20
Curious
  • 20,870
  • 8
  • 61
  • 146

2 Answers2

3

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.

Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175
1

The solution is to recover from the failed state with cin.clear() and then retry to scan till a newline..

Curious
  • 20,870
  • 8
  • 61
  • 146