Я пытаюсь сделать полностью ошибочный ввод для корпусов коммутаторов. Он не должен терпеть неудачу, если пользователь вводит неправильный номер, букву или длинную строку цифр или букв (это то, где раньше были ошибки).
Чтобы предотвратить ошибку, если пользователь вводит, например. "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;
}
EDIT: Я бы хотел, чтобы он принимал только 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
в std::string
с std::getline
, а затем преобразуйте строку в целое число с помощью 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";
}
}
Вы должны использовать std::cin
и проверить его статус:
int choice = -1;
if (cin >> choice)
{
// you know user entered a number, check that it in the correct range
if (cin.peek() != '\n')
// there more input, so probably an error
}
else
{
// bad input
}