在这种情况下如何验证用户输入?

时间:2014-10-07 21:27:35

标签: c++

因此,对于此程序,用户必须输入1到4之间的数字。目前,如果用户错误地输入了不同的数字,程序会提醒用户,但问题是字符。如果用户输入除数字以外的任何类型的字符,则循环变为无限循环。

我想知道是否可以在C ++的介绍级别完成(非常类似于当前代码)

这是代码

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
    int firstNum,
        secondNum,
        subFirstNum,
        subSecNum,
        operNum,
        num;               // User's input answer for operations
    bool temBool = true;   // Temporary boolean used in the while loop
    unsigned seed;         // Random generator seed

    // Use the time function to get a "seed" value for srand
    seed = time(0);
    srand(seed);

    //Start of the loop
    while (temBool) 
    {

    //Random generated operands
    firstNum = rand() % 40 + 10;
    secondNum = rand() % 40 + 10;

    // Set of randoms numbers for substraction where the denominator is always
    // lower than the numerator. 
    subFirstNum = rand() % 30 + 20;
    subSecNum = rand() % 10 + 10;

    // Menu of Math Tutor
    cout << "Math Tutor - Main Menu";
    cout << endl << endl;
    cout << "1. Adittion\n";
    cout << "2. Subtraction\n";
    cout << "3. Multiplication\n";
    cout << "4. Exit Program\n";
    cout << endl << endl;
    cout << "Choose your operation to practice (1-4) ";
    cin >> operNum; 
    cout << endl << endl;

    // Switch for the menu's options
    switch (operNum)
    {
            srand(seed);

    case 1:
        cout << "Working with addition\n";
        cout << setw(3) << firstNum << "\n"
             << "+" << secondNum << "\n"
             << "---\n";
        cout << "Your answer: ";
        cin  >> num;
            if(num == firstNum + secondNum)
            {
                cout << "Correct answer: " 
                     << firstNum + secondNum << " Congratulations!\n";
            }
            else
            {
                cout << "Correct answer: " 
                     << firstNum + secondNum << " Sorry!\n";
            }
        cout << endl << endl;
            break;
    case 2:
        cout << "Working with subtraction\n";
        cout << setw(3) << subFirstNum << "\n"
             << "-" << subSecNum << "\n"
             << "---\n";
        cout << "Your answer: ";
        cin  >> num;
            if(num == subFirstNum - subSecNum)
            {
                cout << "Correct answer: " 
                     << subFirstNum - subSecNum << " Congratulations!\n";
            }
            else
            {
                cout << "Correct answer: " 
                     << subFirstNum + subSecNum << " Sorry!\n";
            }
        cout << endl << endl;
            break;
    case 3:
        cout << "Working with multiplication\n";
        cout << setw(3) << firstNum << "\n"
             << "*" << secondNum << "\n"
             << "---\n";
        cout << "Your answer: ";
        cin  >> num;
            if(num == firstNum * secondNum)
            {
                cout << "Correct answer: " 
                     << firstNum * secondNum << " Congratulations!\n";
            }
            else
            {
                cout << "Correct answer: " 
                     << firstNum * secondNum << " Sorry!\n";
            }
        cout << endl << endl;
            break;
    case 4:
        cout << "Thank you for using Math Tutor.\n\n";
        temBool =  false;
            break;
    default:  
              cout << "Incorrect menu seletion. Please choose between 1 and 4.\n\n";
          break;
    return 0;
    }
    }
}

3 个答案:

答案 0 :(得分:1)

一旦流状态由于无效提取,格式错误等而向南移动,除了检测它之外,你几乎无能为力,确定清除失败状态是否适用,如果是,则继续进行。有时它适用(例如到达EOF;那里不太好)。

这样的事情:

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
    int firstNum,
    secondNum,
    subFirstNum,
    subSecNum,
    operNum,
    num;               // User's input answer for operations
    bool temBool = true;   // Temporary boolean used in the while loop

    // Use the time function to get a "seed" value for srand
    std::srand(static_cast<unsigned>(std::time(nullptr)));

    //Start of the loop
    while (temBool)
    {
        //Random generated operands
        firstNum = rand() % 40 + 10;
        secondNum = rand() % 40 + 10;

        // Set of randoms numbers for substraction where the denominator is always
        // lower than the numerator.
        subFirstNum = rand() % 30 + 20;
        subSecNum = rand() % 10 + 10;

        // Menu of Math Tutor
        cout << "Math Tutor - Main Menu";
        cout << endl << endl;
        cout << "1. Adittion\n";
        cout << "2. Subtraction\n";
        cout << "3. Multiplication\n";
        cout << "4. Exit Program\n";
        cout << endl << endl;
        cout << "Choose your operation to practice (1-4) ";

        // test for successful extraction
        if (!(std::cin >> operNum))
        {
            // yes there are times when you actually use .eof()
            if (std::cin.eof())
                break;

            // flush out the stream through the pending newline
            std::cin.clear();
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            continue;
        }

        cout << endl << endl;

        // Switch for the menu's options
        switch (operNum)
        {
            case 1:
                cout << "Working with addition\n";
                cout << setw(3) << firstNum << "\n"
                << "+" << secondNum << "\n"
                << "---\n";
                cout << "Your answer: ";
                cin  >> num;
                if(num == firstNum + secondNum)
                {
                    cout << "Correct answer: "
                    << firstNum + secondNum << " Congratulations!\n";
                }
                else
                {
                    cout << "Correct answer: "
                    << firstNum + secondNum << " Sorry!\n";
                }
                cout << endl << endl;
                break;
            case 2:
                cout << "Working with subtraction\n";
                cout << setw(3) << subFirstNum << "\n"
                << "-" << subSecNum << "\n"
                << "---\n";
                cout << "Your answer: ";
                cin  >> num;
                if(num == subFirstNum - subSecNum)
                {
                    cout << "Correct answer: "
                    << subFirstNum - subSecNum << " Congratulations!\n";
                }
                else
                {
                    cout << "Correct answer: "
                    << subFirstNum + subSecNum << " Sorry!\n";
                }
                cout << endl << endl;
                break;
            case 3:
                cout << "Working with multiplication\n";
                cout << setw(3) << firstNum << "\n"
                << "*" << secondNum << "\n"
                << "---\n";
                cout << "Your answer: ";
                cin  >> num;
                if(num == firstNum * secondNum)
                {
                    cout << "Correct answer: "
                    << firstNum * secondNum << " Congratulations!\n";
                }
                else
                {
                    cout << "Correct answer: "
                    << firstNum * secondNum << " Sorry!\n";
                }
                cout << endl << endl;
                break;
            case 4:
                cout << "Thank you for using Math Tutor.\n\n";
                temBool =  false;
                break;
            default:  
                cout << "Incorrect menu seletion. Please choose between 1 and 4.\n\n";
                break;
                return 0;
        }
    }
}

答案 1 :(得分:0)

用if语句环绕开关

if (operNum==1||operNum==2||operNum==3||operNum==4){
  ...
}

答案 2 :(得分:0)

我的组织仅为此目的提供以下代码。

#include <cctype>
#include <cstdlib>
#include <string>

/**
 * @brief function returns the integer value of the string entered, negative
       numbers in the input string are not allowed. First non-digit character
       (including minus sign (-)) terminates parsing of the input string
 * @exception throws no exception, return value for every input
 * @param[in] input string containing the response of the user
 * @return <int> errorValue = -1, non-negative value is the response of the user
 */
int menuResponse(std::string input)
{
    int response = 0;
    int length = 0;
    response = atoi(input.c_str());   // <--- magic happens here
    // check for an error in the 1st character itself, only source of false 0 
    // as a response value
    if (isdigit(input[0]))
    {
        return response;
    }
    else
    {
        return -1;
    }
}
相关问题