如何为开关机箱提供可靠的用户输入
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,对于其他所有返回错误输入的内容,请重试。
使用命名空间标准;
int main()
{
string line;
getline(cin, line);
istringstream choice(line);
int number;
choice >> number;
if (choice)
{
if (choice == 1)
{
cout << "you chose option 1n";
//code.....
}
else if (choice == 2)
{
cout<< "you chose option 2n";
//code.....
}
else if (choice == 3)
{
cout<< "you chose option 3n";
//code......
}
}
else
{
cout << "input does not start with a number or is too big for an intn";
}
return 0;
}
用 std::getline
将整行从 std::cin
读到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 numbern";
}
else
{
std::cout << "input okn";
}
}
else
{
std::cerr << "inut does not start with a number or is too big for an intn";
}
}
您应该
使用 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
}
相关文章:
- C++如何通过用户输入删除列表元素
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 如何只允许用户输入正整数
- C++如何计算用户输入的数字中的偶数位数
- 通过for循环使用用户输入填充列表
- 在C++中,我如何接受不同于同一行的用户输入
- 如果用户输入无效,如何使用字符串变量-C++重复输入命令
- 显示基于用户输入的整数的字符
- 根据用户输入用字母填充矢量,并将"开始"和"结束"放在四肢
- 我试图制作一个程序,要求用户输入问题和答案,但程序循环不正确
- 打印时有二叉树问题.用户输入不打印任何内容
- C ++奇怪的数组由用户输入
- 如何允许大写和小写用户输入?
- C++读取用户输入而不按回车键(Mac OS X),与Turbo Pascal中的读取键相同
- 如何存储用户输入的所有数据,然后在他们想要查看所有数据时显示它们
- 如何使用用户输入变量制作二维数组?
- 用户输入字符串的文件附加问题..C++
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- 如何使用递归循环我的代码(当用户输入无效输入时,它会再次提示他们)?