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.
getlinesetsfailbitif the delimiter is not there after the maximum number of characters have been extracted. - L. F.std::cin.clear()regardless of whetherfailbitwas set. - L. F.