而循环意味着不断循环验证用户输入

时间:2015-02-09 15:59:51

标签: c++ while-loop

我正在尝试验证用户输入,但我尝试了两个编译器,我要么发生了两件事之一。它会: - 在不要求用户输入的情况下,不断循环错误消息 要么 - 等待用户输入,如果输入不正确,将不断循环错误消息。

以下是代码:

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)
{ 

userInput声明为整数。是否有更简单的方法来验证用户输入,还是需要while循环?我对编码仍然很陌生。

4 个答案:

答案 0 :(得分:2)

虽然使用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::istringstream与其他输入流类似。它提供来自内部存储器缓冲区的输入,在这种情况下是userInput提供的值。

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

我建议使用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);

答案 3 :(得分:0)

你不想要cin&gt;&gt; int,如果要执行任何错误检查。如果用户输入非整数,您将最终陷入难以恢复的状态。

相反,cin到一个字符串,执行你想要的任何错误检查并将字符串转换为整数:

    long x;
    string sx;
    cin  >> sx;

    x = strtol(sx.c_str(), NULL, 10);
相关问题