我写了一些代码,检查用户是否使用while循环输入了正确的输入类型。问题在于,在您键入的每个错误字符之后,它都会重新循环。
但是,当您输入多个字符时,它将一次又一次地循环相同的cout
语句。例如,如果我键入“qwerty”,当我只希望它运行一次时,它将输出那些 cout`语句6次。
代码如下:
#include <iostream>
using namespace std;
int main(){
// Declare the variables
int choice = 0;
bool valid = false;
while(!valid){
valid = true;
//Ask the user for their choice
cout << "Which function would you like to use? \n";
cout << "1) Average Function \n";
cout << "2) Mean Absolute Deviation Function \n";
cout << "3) Number Sorting Function \n";
cout << "4) Median Function \n";
cout << "5) All of the above \n";
cout << "6) Calculator Function \n";
cout << "Your choice: ";
cin >> choice;
if(cin.fail() || choice > 6 || choice < 1){
cout << "ERROR, PLEASE ENTER ONLY VALID SYMBOLS \n";
cout << "--------------------- \n";
valid = false;
cin.clear();
cin.ignore();
}
}
}
最佳答案
之所以发生循环,是因为在提取一个字符之后,您的cin
缓冲区中还有字符。因此,如果您键入querty<enter>
,则在处理q
之后,仍然需要处理uerty\n
。然后循环,因为它找不到满足您的条件choice > 6 || choice < 1
的输入值,并尝试其他char提取。它可以执行6次,直到缓冲区为空并且设置了cin.fail()
标志。
另一种方法是将整行作为字符串读取,然后从该行中提取一个整数。
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int displayUserInstructions(){
string line;
while(true){
cout << "Which function would you like to use? \n";
cout << "1) Average Function \n";
cout << "2) Mean Absolute Deviation Function \n";
cout << "3) Number Sorting Function \n";
cout << "4) Median Function \n";
cout << "5) All of the above \n";
cout << "6) Calculator Function \n";
cout << "Your choice: ";
if(getline(cin, line)){
stringstream ss(line);
int choice;
if(ss >> choice && (choice >= 1 && choice <= 6)){
return choice;
}
cout << "ERROR, PLEASE ENTER ONLY VALID SYMBOLS \n";
cout << "--------------------- \n";
}
}
}
int main()
{
int choice = displayUserInstructions();
cout << "You made the valid choice of " << choice << '\n';
}