我已經寫了下面的代碼,很大程度上它做我想做的事情。問題是,當用戶可以輸入類似「111」的東西,輸出是「您輸入了數字1」。我想限制用戶的輸入爲1個字符。有什麼建議麼?我確信解決方案非常簡單,但我無法弄清楚。此外,代碼必須以switch語句的形式保留。謝謝!限制用戶輸入
#include <iostream>
using namespace std;
int main()
{
char i;
cout << "Please enter a number between 1 and 9." << endl;
cout << "Enter a number: ";
cin >> i;
switch (i)
{
case '1':
cout << "You entered the number one." << endl;
break;
case '2':
cout << "You entered the number two." << endl;
break;
case '3':
cout << "You entered the number three." << endl;
break;
case '4':
cout << "You entered the number four." << endl;
break;
case '5':
cout << "You entered the number five." << endl;
break;
case '6':
cout << "You entered the number six." << endl;
break;
case '7':
cout << "You entered the number seven." << endl;
break;
case '8':
cout << "You entered the number eight." << endl;
break;
case '9':
cout << "You entered the number nine." << endl;
break;
default:
cout << "You did not enter a valid number." << endl;
break;
}
system("pause");
return 0;
}
您已將輸入限制爲一個字符。沒有辦法阻止他們在標準C++中再打字。 – chris
你的輸入形式是什麼? – durbnpoisn
在控制檯中,用戶可以鍵入任意數量或字符。例如。如果用戶鍵入a,則輸出將爲「您沒有輸入有效的號碼。」另一個例子是,如果用戶鍵入19,那麼程序將輸出「您輸入了數字1」。數字1是用戶輸入的第一個字符。問題是我希望程序拒絕任何不在1到9之間的數字。我有道理嗎? – user3727648