C++ While循环意味着不断验证用户输入

C++ While循环意味着不断验证用户输入,c++,while-loop,C++,While Loop,我正在尝试验证用户输入,但我已经尝试了两个编译器,并且出现了两种情况之一。它将: -不断循环错误消息,而不要求用户输入 或 -等待用户输入,如果输入不正确,将不断循环错误消息 代码如下: cout << "Input number of the equation you want to use (1,2,3): " ; cin >> userInput; cout << endl; while (userInput <= 0 || userInput

我正在尝试验证用户输入,但我已经尝试了两个编译器,并且出现了两种情况之一。它将: -不断循环错误消息,而不要求用户输入 或 -等待用户输入,如果输入不正确,将不断循环错误消息

代码如下:

cout << "Input number of the equation you want to use (1,2,3): " ;
cin >> userInput;
cout << endl;

while (userInput <= 0 || userInput >= 4)
{
    cout << "Please enter a correct input (1,2,3): " ;
    cin >> userInput;
    cout << endl;
}

if (userInput == 1)
{ 
cout>userInput;
cout用户输入;

cout我将添加一个额外的检查,以确保如果用户输入非整数输入,则在尝试下一次读取之前清除流

cout << "Input number of the equation you want to use (1,2,3): " ;
cin >> userInput;
cout << endl;

while (userInput <= 0 || userInput >= 4)
{
   if ( !cin.good() )
   {
      cin.clear();
      cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
   }

   cout << "Please enter a correct input (1,2,3): " ;
   cin >> userInput;
   cout << endl;
}
cout>userInput;
cout用户输入;

cout我建议使用do循环,这样重复的行就少了

int userInput = 0;
do
{
   cout << "Input number of the equation you want to use (1,2,3): " ;
   cin >> userInput;
   cout << endl;
   if ( !cin.good() )
   {
      cin.clear();
      cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
   }
} while (userInput <= 0 || userInput >= 4);
int userInput=0;
做
{
cout>userInput;

cout如果要执行任何错误检查,您不希望使用cin>>int。如果用户输入非整数,您将很难从这种情况中恢复

而是将cin转换为字符串,执行所需的任何错误检查,并将字符串转换为整数:

    long x;
    string sx;
    cin  >> sx;

    x = strtol(sx.c_str(), NULL, 10);

虽然使用
int userInput
似乎很简单,但当用户输入非数值时,它会失败。您可以使用
std::string
来代替,并检查它是否包含数值

std::string userInput;
int value;
std::cout << "Input number of the equation you want to use (1,2,3): " ;
while (std::cin >> userInput) {
    std::istringstream s(userInput);
    s >> value;
    if (value >= 1 && value <= 3)
        break;

    std::cout << "Please enter a correct input (1,2,3): " ;
}
std::字符串用户输入;
int值;
std::cout>userInput){
std::istringstreams(用户输入);
s>>价值;

如果(value>=1&&value对我来说似乎是直截了当的,我看不出有什么问题。R Sahu的可能重复:你能解释一下你的意思吗?这是为了防止程序在用户输入字符而不是整数时无限循环,还是一种清理之类的事情?…我很困惑,如果我不理解,很抱歉:我不熟悉cin.good、clear或ignore第一个。不要抱歉。当你没有遵循问题或答案时,寻求澄清对于高效沟通至关重要。如果我将cin更改为字符串,我将如何使其验证用户输入?我需要花一段时间吗(userInput不是1,2,3)或者类似的事情?我不知道怎么做这看起来很好,因为它会检查任何值,而不仅仅是整数。如果可以,你能计算istringstream是什么,以及“s”吗?我想我会这样做,但我想知道这些命令是什么,因为我不熟悉它们