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

时间:2013-09-19 13:26:50

标签: c++ loops cin

我的代码: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语句来检查正确性,它运行正常。然而,无论我尝试什么,当我实现该部分时,它要么变成无限循环,要么无法获胜。如果有人能让我知道这有什么问题我会非常感激,因为我不能为我的生活想出这一点。

2 个答案:

答案 0 :(得分:1)

只是看看你的代码......我想

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

答案 1 :(得分:0)

您的支票可以这样实现:

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

我不确定你为什么要达到峰值并寻找行尾

相关问题