简体   繁体   English

如何修复我的代码中的无限循环? 我认为它跳过了第二个cin,所以它一直循环播放

[英]How to fix the infinity loop in my code? I think it skips the second cin so it keeps looping

If i the input is not an int, it's going to give a infinite loop, i think it skips the second cin, but i don't know how to fix it. 如果我的输入不是整数,它将给出一个无限循环,我认为它会跳过第二个cin,但我不知道如何解决。

cout << "Number of days : ";
int days;
cin >> days;
while(!cin){
    cout << "Invalid";
    cin >> days;
}

When operator>> fails to parse input, it puts the stream into an error state that you need to explicitly clear before you can read from the stream again, eg: operator>>无法解析输入时,它会将流置于错误状态,您需要先清除该错误状态,然后才能再次从流中读取,例如:

cout << "Number of days : ";
int days;
while (!(cin >> days)) {
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cout << "Invalid";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM