如何将输入仅限于数字 [英] How to Limit Input to Numbers Only

查看:125
本文介绍了如何将输入仅限于数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近创建了一个程序,将根据用户输入创建一个数学问题。通过输入1-4,程序可能产生问题,或者用户可以通过输入5退出。我遇到的唯一问题是,当我输入一个字符,程序进入无限循环。我可以使用什么函数来检查输入是否不是数字,因此我可以显示错误消息?

I recently created a program that will create a math problem based on the user input. By entering either 1-4 the program can generate a problem or the user can quit by entering 5. The only problem I am having is that when I enter a character the program goes into an infinite loop. What function could I use to check if the input is not a number so I can display an error message?

//CIS180 Assignment #4
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
    //Declare variables.
    int num1, num2, menuNum;
    int addInput, subInput, multInput, divInput;
    int addAnswer, subAnswer, multAnswer, divAnswer;
    int addSolution, subSolution, multSolution, divSolution;
    srand(time(0));
    //Display menu.
    cout << "Menu" << endl;
    cout << "1. Addition problem" << endl;
    cout << "2. Subtraction problem" << endl;
    cout << "3. Multiplication problem" << endl;
    cout << "4. Division problem" << endl;
    cout << "5. Quit this program" << endl << endl;
    cout << "Enter your choice (1-5): " << endl;
    cin >> menuNum;
    //Loop that will provide math problems when user inputs number.
    while(menuNum != 5)
    {
        //Check if the input is valid.
        while((menuNum < 1) || (menuNum >5))
        {
            cout << "The valid choices are 1, 2, 3 , 4, and 5. Please choose: " << endl;
            cin >> menuNum;
        }
        //Generate two random numbers for addition and display output.
        if(menuNum == 1)
        {
            num1 = rand()%500 + 1;
            num2 = rand()%500 + 1;
            addSolution = num1 + num2;
            cout << setw(5) << right << num1 << endl;
            cout << setw(2) << left << "+" << setw(3) << right << num2 << endl;
            cout << setw(5) << fixed << "-----" << endl;
            cin >> addAnswer;
            //Check if the addition answer input is correct.
            if(addAnswer != addSolution)
                cout << "Sorry, the correct answer is " << addSolution << "." << endl;
            else if(addAnswer == addSolution)
                cout << "Congratulations! That's right." << endl << endl;
        }
        .
            .
            .


推荐答案

首先,您应该检测您的输入尝试是否成功:始终,在之后检查读取尝试成功。接下来,当您确定您无法读取值时,您需要使用 clear()将流重置为一个良好的状态,您需要清除的任何错误字符,例如,使用 ignore()。假定字符通常被输入,即,用户在字符被使用之前必须命中返回,则通常可以重新获得整个行。例如:

First off, you should detect whether your input attempt was successful: always check after reading that the read attempt was successful. Next, when you identify that you couldn't read a value you'll need to reset the stream to a good state using clear() and you'll need to get rid of any bad characters, e.g., using ignore(). Given that the characters were typically entered, i.e., the user had to hit return before the characters were used it is generally reaonable to get of the entire line. For example:

for (choice = -1; !(1 <= choice && choice <= 5); ) {
    if (!(std::cin >> choice)) {
         std::cout << "invalid character was added (ignoring the line)\n";
         std::cin.clear();
         std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }

}

使用 std :: numeric_limits< std :: streamsize> :: max()是获取幻数的方法, 在找到具有其第二个参数的值的字符之前,必须有足够多的字符。

The use of std::numeric_limits<std::streamsize>::max() is the way to obtain the magic number which makes ignore() as many characters as necessary until a character with the value of its second argument is found.

这篇关于如何将输入仅限于数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆