cin.get infinite loop




#include <iostream>
#include <string>
using namespace std;
int main () {
char a[20];
for (;;) {
cout << "ENTER: ";
cin.getline(a, 10);
cout << a << endl;
}
}



This program gives me infinite "ENTER: " once it gets to cin.getline(a, 10);
Why would it go infinite loop and not wait for my input for each loop?





Last edited on
It works fine for me.

By best guess is that somehow the input stream is corrupted, so that the failbit or eofbit or badbit etc is set somewhere in the loop, which will cause all further attempts to getline() to be ignored.

Try adding a clear() and see if that helps:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>
using namespace std;

int main () {
  char a[20];
  for (; !cin.eof();) {  // <--
    cout << "ENTER: ";
    cin.clear();         // <--
    cin.getline(a, 10);
    cout << a << endl;
    }
  cout << "All done." << endl;
  return 0;
  }


Hope this helps.
Last edited on
Topic archived. No new replies allowed.