循环直到整数输入在所需范围内无法处理非数字字符输入

Loop until integer input is in required range fails to work with non-digit character inputs

本文关键字:处理 字符输入 数字 范围内 整数 输入 循环      更新时间:2023-10-16

我对应该非常简单的代码有问题。 我想通过错误检查接收一个介于 1 和 3 之间的整数。 它适用于检查太大或太小的数字,但是当输入字母/数字组合时,它会卡在无限循环中。 建议?

#include <iostream>
using namespace std;
int main(int argc, char *argv[]){
int input;
cout << "nPlease enter a number from 1 to 3:" << endl;
cout << "-> ";
cin >> input;
while(input< 1 || input> 3){
cout << "n---------------------------------------" << endl;
cout << "n[!] The number you entered was invalid." << endl;
cout << "nPlease re-enter a number from 1 to 3" << endl;
cout << "-> ";
cin >> input;
}
cout << "You chose " << input << endl;
}

问题是:

cin >> input;

将导致在尝试读取非数值时设置坏位。发生这种情况后,任何使用该operator>>的尝试都将被静默忽略。

因此,纠正此问题的方法是测试流是否处于良好状态,如果不是,则重置状态标志并尝试再次读取。但请注意,错误的输入(导致问题)仍在输入上,因此您需要确保也将其丢弃。

if (cin >> input)
{
// It worked (input is now in a good state)
}
else
{
// input is in a bad state.
// So first clear the state.
cin.clear();
// Now you must get rid of the bad input.
// Personally I would just ignore the rest of the line
cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
// now that you have reset the stream you can go back and try and read again.
}

为了防止它卡住(这是由设置的坏位引起的),读入字符串,然后使用字符串流来解析用户输入。我也更喜欢这种方法(用于用户交互式输入),因为它允许更容易地组合不同的阅读风格(即结合operator>>std::getline(),因为您可以在字符串流上使用它们)。

#include <iostream>
#include <sstream>
#include <string>
// using namespace std;
// Try to stop using this.
// For anything other than a toy program it becomes a problem.
int main(int argc, char *argv[])
{
int          input;
std::string  line;
while(std::getline(std::cin, line))   // read a line at a time for parsing.
{
std::stringstream linestream(line);
if (!(linestream >> input))
{
// input was not a number
// Error message and try again
continue;
}
if ((input < 1) || (input > 3))
{
// Error out of range
// Message and try again
continue;
}
char errorTest;
if (linestream >> errorTest)
{
// There was extra stuff on the same line.
// ie sobody typed 2x<enter>
// Error Message;
continue;
}
// it worked perfectly.
// The value is now in input.
// So break out of the loop. 
break;
}
}
#include <iostream>
#include <string>
using namespace std;
int validatedInput(int min = 1, int max = 3)
{
while(true)
{
cout << "Enter a number: ";
string s;
getline(cin,s);
char *endp = 0;
int ret = strtol(s.c_str(),&endp,10);
if(endp!=s.c_str() && !*endp && ret >= min && ret <= max)
return ret;
cout << "Invalid input. Allowed range: " << min << "-" << max <<endl;
}
}
int main(int argc, char *argv[])
{
int val = validatedInput();
cout << "You entered " << val <<endl;
return 0;
}

这些答案中的大多数都包含不必要的复杂性。

输入验证是使用 do-while 的最佳时机

do{
cout << "nPlease enter a number from 1 to 3:" << endl;
cout << "-> ";
if(!cin){
cout << "Invalid input"
cin.clear()
cin.ignore(numeric_limits<streamsize>::max(), 'n');
}
}while(!(cin >> input))
  • 使用numeric_limits<streamsize>::max()完全清除cin失败后的缓冲区。

  • 使用cin.clear()重置cin上的失败标志,以便!cin不会 总是评估错误。

cin.fail()很好。然而,有些人会认为!cin更自然。

从我之前的帖子 https://stackoverflow.com/a/43421325/5890809

您将输入声明为 int,但是当您编写字母数字字符进行输入时,它将尝试将其隐式转换为整数。但是您的错误检查并不能说明这一点。

您的问题可以通过更改 while 循环轻松解决。 而不是检查这个,你检查一下怎么样

while(input!=1 || input!=2 || input!=3)