我想爲開關盒做一個完全防錯輸入。如果用戶輸入錯誤的數字,字母或長串數字或字母(這是我之前有過錯誤的地方),它不會失敗。如何爲開關盒提供強大的用戶輸入?
防止錯誤,如果用戶輸入,例如。 "asdghdk3"
我曾嘗試使用數組,因此它會檢查每個字母,直到它找到一個數字。
我試圖把它變成一個整數的開關情況。 可悲的是我的代碼不起作用。有沒有人有任何建議或改進? 謝謝。
#include <iostream>
#include <vector>
#include <cmath>
#include <cstdlib>
using namespace std;
int main()
{
cout<<"Please choose the method you would like to use to evaluate the potential. Please enter 1,2 or 3:"<<endl;
cout<<"1. my method. \n2. jacobi method. \n3. Exit programme. \nYou chose: ";
char choice[20];
bool k = true;
int choice2;
while (k == true){
fgets(choice, sizeof choice, stdin);
for(int j=0; j<sizeof(choice); j++){
if (isdigit(choice[j])==true){ //I want it to check every character until it finds a number.
choice2 = atoi(choice[j]); //changed name as now integer to be used in switch case.
k = false;
break; //so that it breaks out of the for loops because it has found a number
}
else{
continue;
}
}
cout<<"Incorrect input please try again";
}
cout<<"\nchoice2= "<<choice2<<endl;
switch (choice2) {
case 1 :
// Code
break;
case 2:
// Code
break;
case 3:
//code to exit programme
break;
default:
// Code
break;
}
return 0;
}
編輯: 我想它只能接受1,2或3,其他一切返回不正確的輸入,請重試。
using namespace std;
int main()
{
string line;
getline(cin, line);
istringstream choice(line);
int number;
choice >> number;
if (choice)
{
if (choice == 1)
{
cout << "you chose option 1\n";
//code.....
}
else if (choice == 2)
{
cout<< "you chose option 2\n";
//code.....
}
else if (choice == 3)
{
cout<< "you chose option 3\n";
//code......
}
}
else
{
cout << "input does not start with a number or is too big for an int\n";
}
return 0;
}
對不起,我忘了補充一點,這並不工作,因爲現在的選擇其實不是我的號碼,我想。 爲了解決這個問題,我試着在if語句中改變選擇號碼。 – user3343772
在您編輯的代碼中,您將流本身與1,2和3進行比較,而不是輸入的數字!這是錯誤的。只需按照我答案中的示例進行操作,然後在最裏面的部分(其中字符串流已經針對eof進行了檢查並打印了「輸入ok」),請將數字變量與1,2或3進行比較。 –
Hi Christian , 感謝這個現在的作品,差不多!我改變了它,所以其中一個選項是零。唯一的問題是,如果輸入0,那麼它返回「輸入不以數字開始......」 對於字符串中的正常數字,零是否被區別對待? 我該如何解決這個問題?謝謝。 – user3343772