检查有效的 CIN 输入时出现问题

Problems checking for valid cin input

本文关键字:问题 输入 有效 CIN 检查      更新时间:2023-10-16

我的代码:http://pastebin.com/qjFd6KXb

有一个课程作业,要求我创建一个程序,该程序将输出一个简单的乘法问题,用户必须在三次或更少的尝试中回答。其中一个要求是程序检查用户猜测是否为有效数字。我的教授希望我们在代码中使用此方法:

#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
    char c;
    bool valid = false;
    int i;
    while (!valid)
    {
        cout << "Enter an int " << endl;
        cin >> i;
        valid = true;
        if (cin.peek() != 'n' || cin.fail()) // checks if the input data was correct or not
        {
            valid = false; 
            cin.clear();  // clears the error flags
            cin.ignore(100, 'n'); // ignores up to 100 characters in the cin stream
        }
    }
}

我的问题出现在我的代码的第 57 行左右。没有额外的 while 循环和 if 语句来检查正确性,它运行良好。然而,无论我尝试什么,当我实现该部分时,它要么变成无限循环,要么不可能获胜。如果有人能让我知道这有什么问题,我将不胜感激,因为我一生都无法弄清楚这个问题。

只是简单地

看了一下你的代码。我认为

tries = tries + 1; // Adds one to the tries counter

在错误的范围内

while ((choice != 1) || (choice != 1) || (choice != 1));   
   cout << "Try to solve the problem!n"; // Provides instruction to the user.
   while ((result != guess) && (tries < maxtries))
   {
   }  
   tries = tries + 1; // Adds one to the tries counter
}

应该是

while (choice != 1);   
   cout << "Try to solve the problem!n"; // Provides instruction to the user.
   while ((result != guess) && (tries < maxtries))
   {
          tries = tries + 1; // Adds one to the tries counter
   }  
}

您的检查可以像这样实现:

    std::cin >> i;
    while( std::cin.fail() ) {
        std::cout << "Bad InputnEnter an Integer, foo: ";
        std::cin.clear();
        std::cin.ignore('256','n');
        std::cin >> i;
    }

我不确定你为什么要达到顶峰并寻找终点