2017-12-07 1 views
0

無効な入力データタイプのチェックを1回実行しようとしています。入力データ型が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

+0

「try」と「catch」節を使用すると、無効な文字を入力すると例外が発生します。 – Rafalsonn

+0

どのようにわからないのですか。 –

+0

例外を書くコンソールに入ると助けてくれると思います – Rafalsonn

答えて

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)

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; 
/////////////////////////////////////////////////// 
+1

それはどのように解決されますか? – kishore

関連する問題