When the t variable is within int bounds, getline input behavior is fine. but when the value given to t is out of int bounds, getline behavior is weird
why so ?
cin>>t;
string s(10, '&');
getline(cin, s);
cout<<s<<endl;
if input is:
100
hey hi
output is:
hey hi
if input is:
1234567891011
hey hi
output is:
&&&&&&&&&&
if input is:
1234567891011
hey hi
i was expecting hey hi
as an output
When the t variable is within int bounds, getline input behavior is fine. but when the value given to t is out of int bounds, getline behavior is weird
why so ?
cin>>t;
string s(10, '&');
getline(cin, s);
cout<<s<<endl;
if input is:
100
hey hi
output is:
hey hi
if input is:
1234567891011
hey hi
output is:
&&&&&&&&&&
if input is:
1234567891011
hey hi
i was expecting hey hi
as an output
- 5 Could it be that the input is in an error state after an invalid input is attempted? Your code doesn't test the stream after the input attempt. – Thomas Matthews Commented Mar 31 at 17:56
- 2 I would have expected the first input presented to fail because of Why does std::getline() skip input after a formatted extraction?. Example: godbolt./z/74f3TdTW5 – user4581301 Commented Mar 31 at 18:20
1 Answer
Reset to default 1If cin>>t
fails, the std::cin
stream is put into an error state that you are not clearing. Thus, the subsequent std::getline()
also fails, and leaves your s
variable unchanged. You should always check for input failures, and clear errors when needed, eg:
cout << "Enter an integer: ";
while (!(cin >> t)) {
// clear the error state
cin.clear();
// remove garbage input
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Enter a VALID integer!: ";
}
string s;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
if (getline(cin, s)) {
cout << "You entered: " << s << endl;
}
else {
// input failed ...
}
// OR:
string s;
if (getline(cin >> ws, s)) {
cout << "You entered: " << s << endl;
}
else {
// input failed ...
}