【问题标题】:How to continue looping after invalid data type input?输入无效数据类型后如何继续循环?
【发布时间】:2017-12-07 06:25:30
【问题描述】:

我正在尝试检查无效的输入数据类型。如果输入数据类型是 char 类型,我希望重新循环菜单选项。但是我的程序反而终止了。

int menu()
{
    int choice = 15;
    while ((choice > 14) || ( choice < 0))
    {
        cout << "Enter 0 to quit\n";
        cout << "Enter 1 for Addition\n";
        cout << "Enter 2 for Subtraction\n";
        cout << "Enter 3 for Multiplication\n";
        cout << "Enter 4 for Division of two integers\n";
        cout << "Enter 5 for Real Division of two integers\n";
        cout << "Enter 6 for Quotient of a division\n";
        cout << "Enter 7 for Remainder of a division\n";
        cout << "Enter 8 for Factorial of an integer\n";
        cout << "Enter 9 for Exponential of two integers\n";
        cout << "Enter 10 for Finding if number is even or odd\n";
        cout << "Enter 11 for Area of a Square\n";
        cout << "Enter 12 for Area of a Circle\n";
        cout << "Enter 13 for Area of an Isoceles Triangle\n";
        cout << "Enter 14 for Converting Decimal to binary or hexadecimal\n";
        cin >> choice;

        if((choice > 14) || (choice < 0))
        {
            cout << "Invalid entry: Try again" << endl << endl;
        }
        else if ( !choice ) 
        {
            return choice;
        }
        else if (choice)
        {
            return choice;
        }
    }

    return choice;
}

Output after entering char 'f' as cin

【问题讨论】:

  • 使用“try”和“catch”子句,使用输入无效字符时得到的异常
  • 我不知道怎么做。
  • 写异常你进入控制台,我想我可以帮忙
  • 调试您的程序,检查正在执行的返回语句,并更改它以处理您希望避免返回的情况(顺便说一句,您可能希望将 choice 初始化为某种“非法”值,然后再从用户那里扫描)。

标签: c++


【解决方案1】:

试试这个

if (cin >> choice)
{
    if((choice > 14) || (choice < 0))
        cout << "Invalid entry: Try again" << endl << endl;
    else
        return choice;
}
else //Fail to cin into choice, user input is not a number
    cout << "Invalid entry: Please key in a number." << endl;

另外,while 条件应更改为 while (true)

【讨论】:

    【解决方案2】:

    删除空格线,然后再次运行代码。

    if((choice > 14) || (choice < 0))
        cout << "Invalid entry: Try again" << endl << endl;
    
    else if ( !choice ) 
    {
     return choice;
    }
    ////// remove the empty space line below///////////
    else if (choice)
        return choice;
    ///////////////////////////////////////////////////
    

    【讨论】:

    • 解决方案如何?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-08
    • 2017-02-25
    • 1970-01-01
    • 2018-03-20
    • 2021-03-25
    • 2015-04-29
    • 1970-01-01
    相关资源
    最近更新 更多