[英]How to make a robust user input for a switch case?
我正在嘗試為開關盒提供完全防錯的輸入。 如果用戶輸入了錯誤的數字,字母或一長串數字或字母(這是我之前遇到過錯誤的地方),它就不會失敗。
為了防止錯誤,如果用戶輸入例如 我嘗試使用"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,對於其他所有返回錯誤輸入的內容,請重試。
使用名稱空間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;
}
您應該使用std::cin
並檢查其狀態:
int choice = -1;
if (cin >> choice)
{
// you know user entered a number, check that it's in the correct range
if (cin.peek() != '\n')
// there's more input, so probably an error
}
else
{
// bad input
}
將std::cin
的整行讀取為帶有std::getline
的std::string
,然后使用std::istringstream
將行轉換為整數。 最后,在轉換之后,檢查字符串流中是否還有字符。 這是一個完整的示例:
#include <iostream>
#include <sstream>
#include <string>
int main()
{
std::string line;
std::getline(std::cin, line);
std::istringstream is(line);
int number;
is >> number;
if (is)
{
if (!is.eof())
{
std::cerr << "input does not end with a number\n";
}
else
{
std::cout << "input ok\n";
}
}
else
{
std::cerr << "inut does not start with a number or is too big for an int\n";
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.