gpt4 book ai didi

c++ - 循环直到整数输入在要求的范围内无法处理非数字字符输入

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:08:06 32 4
gpt4 key购买 nike

我对应该非常简单的代码有疑问。我想通过错误检查获取 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() 作为你可以在 stringstream 上使用这些)。

#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;
}
}

关于c++ - 循环直到整数输入在要求的范围内无法处理非数字字符输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13212043/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com