最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c++ - Why getline is not inputting when previous cin is integer overflow - Stack Overflow

programmeradmin2浏览0评论

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

Share Improve this question edited Mar 31 at 18:10 genpfault 52.2k12 gold badges91 silver badges151 bronze badges asked Mar 31 at 17:46 Rohith chiduralaRohith chidurala 313 bronze badges 2
  • 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
Add a comment  | 

1 Answer 1

Reset to default 1

If 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 ...
}
发布评论

评论列表(0)

  1. 暂无评论