Search code examples
c++inputiocin

How to make cin work after using getline?


So, I read a string using cin.getline(str,10,'h') where as you can see I have used a custom delimiter 'h' and want to read a maximum of 9 characters. After doing this, I use cin>>n to read an integer into my int variable n.

#include <iostream>
using namespace std;
int main() {
    int n;
    char str[100];
    cin.getline(str, 10, 'h');
    cout<<str<<'-'<<endl;
    cout<<"Enter a number:";
    cin>>n;
    cout<<n;
    return 0;
}

Suppose I pass the following input


2 3   pl32

which is a '\n' followed by "2 3 pl32". I expect getline to read the string "\n2 3 pl" and then cin to read the integer 32. But that's isn't what happened.

The actual output showed that the cin read garbage value:


2 3   pl-
Enter a number:0

Edit: Ok, so I get it now. Getline set the failbit , that's what caused the issue. Problem solved.


Solution

  • The problem is that getline has not found its delimiter, and has set the failbit flag in cin. You must clear the flag to read again on the stream:

    ...
    cin.getline(str, 10, 'h');
    cin.clear();                  # reset a possible error condition
    cout<<str<<'-'<<endl;
    cout<<"Enter a number:";
    cin>>n;
    ...