【问题标题】:How to Limit Input to Numbers Only如何将输入限制为仅数字
【发布时间】:2013-09-21 19:23:50
【问题描述】:

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


//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;
        }
        .
            .
            .

【问题讨论】:

  • 你能把问题从 100 多行代码缩小吗?
  • 顺便说一句,您不需要在程序的开头声明所有变量。相反,在实际使用它们的地方声明它们。这样你仍然会记得 menuNum 是一个 int 并且你不会忘记初始化它们。

标签: c++ validation input numbers character


【解决方案1】:

首先,您应该检测您的输入尝试是否成功:始终检查 after 读取读取尝试是否成功。接下来,当您确定无法读取某个值时,您需要使用clear() 将流重置为良好状态,并且您需要删除任何错误字符,例如使用ignore()。鉴于通常输入字符,即用户必须在使用字符之前按回车键,因此通常可以获取整行。例如:

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&lt;std::streamsize&gt;::max() 是获取幻数的方法,它使ignore() 的字符数尽可能多,直到找到具有第二个参数值的字符。

【讨论】:

  • 非常感谢!这非常有帮助。
【解决方案2】:
  1. 读取单个字符
  2. 如果此字符是数字,请使用它。
  3. 如果此字符不是数字,请转到 1。

实际上,忘记第 2 步。只需检查它是否是您真正想要的数字字符之一('1''2''3''4''5'):

char choice;

while(cin.get(choice)){
  if(choice == '5')
    break;

  switch(choice){
    default: printWrongCharacterMessage(); break;
    case '1': do1Stuff(); break;
    case '2': do2Stuff(); break;
    case '3': do3Stuff(); break;
    case '4': do4Stuff(); break;    
  }
}

【讨论】:

  • 这个解决方案很难扩展到两位数的选择。 Dietmar Kuhl 的解决方案更好。输入一个整数,测试是否成功。
  • 虽然我没有专门使用你提供的代码,但是很有帮助。我只是简单地声明了 char menuNum[4],因为它不会用于计算并相应地更改了其余部分,现在它工作得很好。谢谢!
  • @ThomasMatthews:这个解决方案并不意味着扩展到两位数的选择。 Dietmar 的解决方案是不同的(在我看来,对于个位数来说有点太多了),这就是为什么我发布这个答案而不是你的标准“阅读、测试、清除”例程。两者都是有效的;)。
【解决方案3】:

您可以使用 ctype.h 中的isdigit

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-14
    • 1970-01-01
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-26
    • 2013-08-21
    相关资源
    最近更新 更多