我试图检查无效的输入数据类型。如果输入数据类型是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;
}
答案 0 :(得分:0)
试试这个
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)
答案 1 :(得分:0)
删除空格行,然后再次运行代码。
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;
///////////////////////////////////////////////////