0
votes

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.

1
The delimiter 'h' wasn't used. But since the second argument provided was 10, the getline should just read the first 9 characters it encounters and then stop. And, that's what happened. - Shashank Kumar
getline sets failbit if the delimiter is not there after the maximum number of characters have been extracted. - L. F.
@L.F. So, suppose I want to read until either 9 characters have been read or the delimiter is encountered. Now, getline doesn't work since it sets the failbit, so how to get around the problem? I suppose, one way is to check if the failbit is set and if that's the case, unset it again? - Shashank Kumar
Yep. You can just use std::cin.clear() regardless of whether failbit was set. - L. F.

1 Answers

1
votes

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;
...