簡體   English   中英

在這種情況下如何驗證用戶輸入?

[英]How to validate the user input in this case?

因此,對於此程序,用戶必須輸入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;
    }
    }
}

一旦流狀態由於無效的提取,格式錯誤等原因而向南移動,除了檢測到故障,確定清除故障狀態是否適用,進行故障清除並繼續操作之外,您幾乎無能為力。 有時它適用(例如到達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;
        }
    }
}

用if語句包圍開關

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

我的組織僅出於以下目的使用以下代碼。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM