std::cin无限循环错误输入
std::cin infinite loop for wrong input
在下面的代码中,我想循环直到用户提供正确的输入。但当我尝试的时候,它变成了一个不停的循环Please Enter Valid Input.
如果没有while循环,它也是一样的。
此处带有while循环:
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <sstream>
using namespace std;
class library {
public:
library() {
int mainOption;
cout<<"Please choose the option you want to perform."<<endl;
cout<<"1. Member Section"<<"n"<<"2. Books, Lending & Donate Section"<<"n"<<"3. Returning Section"<<endl;
bool option=true;
while (option==true) {
cin>>mainOption;
if (mainOption==1) {
cout<<"section 1"<<endl;
option=false;
} else if (mainOption==2) {
cout<<"section 1"<<endl;
option=false;
} else if (mainOption==3) {
cout<<"section 1"<<endl;
option=false;
} else {
cout<<"Please Enter Valid Input. "<<endl;
//option still true. so it should ask user input again right?
}
}
}
};
int main(int argc, const char * argv[])
{
library l1;
return 0;
}
这里没有while循环。但同样的事情正在发生。
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <sstream>
using namespace std;
class library {
public:
library() {
int mainOption;
cout<<"Please choose the option you want to perform."<<endl;
cout<<"1. Member Section"<<"n"<<"2. Books, Lending & Donate Section"<<"n"<<"3. Returning Section"<<endl;
cin>>mainOption;
if (mainOption==1) {
cout<<"section 1"<<endl;
} else if (mainOption==2) {
cout<<"section 1"<<endl;
} else if (mainOption==3) {
cout<<"section 1"<<endl;
} else {
cout<<"Please Enter Valid Input. "<<endl;
library();//Calling library function again to input again.
}
}
};
int main(int argc, const char * argv[])
{
library l1;
return 0;
}
问题是当您调用时
cin>>mainOption; // mainOption is an int
但是用户不而输入int
、cin
使输入缓冲器处于旧状态。除非您的代码消耗了输入的无效部分,否则最终用户输入的错误值将保留在缓冲区中,从而导致无限重复。
以下是解决此问题的方法:
} else {
cout<<"Please Enter Valid Input. "<<endl;
cin.clear(); // Clear the error state
string discard;
getline(cin, discard); // Read and discard the next line
// option remains true, so the loop continues
}
注意,我还删除了递归,因为while
循环足够好,可以处理手头的任务。
相关文章:
- 堆栈中大小变量输入错误 (C++)
- 如果用户没有输入任何内容或输入错误,如何重新输入用户的输入?
- 如何从标准输入中检测格式化输入错误?
- 如何在没有打印语句的情况下报告用户输入错误
- 用户输入错误
- 按下Enter时如何输入错误消息,但没有给出任何答案
- 在我的IF-ELSE循环中输入错误
- C++ 输入错误
- C++ 函数输入错误
- 使用ifstreamwhile循环,如何显示输入错误并在下一行继续
- switch 语句中的输入错误 如何循环回第一种情况?C++
- 在 switch 语句中输入字符以进行C++时用户输入错误
- 如果我输入错误的 dos 命令,shellexecute 会给出正确的结果
- C++输入错误的数组
- scanf和多个输入错误
- C++输入浮点而不是整数时的输入错误
- 使用字符串流和if-else语句时发生字符串输入错误
- 当用户输入错误输入时,一次清除 cin 中的整行而不是一个字符
- setw() 在包含 UTF-8 多字节字符/码位的字符串上输入错误的输出
- c++中的getline输入错误