带有菜单的c++输入验证
input validation c++ with menu
我的菜单是这样的
int choice;
cout <<"1: Exitn2: Print Markn3: Print Name"<<endl;
cin >> choice;
while (choice != 1 && choice != 2 && choice != 3)
{
cout << "Invalid Choice <<endl;
cout <<"1: Exitn2: Print Markn3: Print Name"<<endl;
cin >> choice;
}
,这就是我到目前为止所拥有的,但是当我输入字母时,它终止了,有没有一种更简单的方法来测试无效输入。我知道有一种东西叫"失败"。但不确定如何实现
这个简单的行跳转当它是一个不好的输入
td::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n'); // ignore and skip bad input
好的,你可以这样构建你的代码
do {
if (choice ==1)
{
exit(1);
}else if (choice==2)
{
//code
}
}else if (choice==3)
{
//code
}
}else if (choice==4)
{
//code
}else{
cout <<"Please enter a correct option"<<endl;
cin.clear();
string choice;
cin>>choice;
}
}while(!cin.fail())
如果可以将整型转换为char,可以这样做。这样很容易。
char choice;
cout <<"1: Exitn2: Print Markn3: Print Name"<<endl;
cin >> choice;
while (choice != '1' && choice != '2' && choice != '3')
{
cout << "Invalid Choice <<endl;
cout <<"1: Exitn2: Print Markn3: Print Name"<<endl;
cin >> choice;
}
如果你想把选择值恢复为整型,你可以使用
int choiceInt = choice - '0';
首先接受一个字符串作为输入,然后尝试将其强制转换为int,看看它是否有效。你可以这样做(如果使用c++11):
#include <iostream>
#include <cstring>
using namespace std;
int main() {
int choice = -1;
while (true) {
string input;
cout << "1: Exitn2: Print Markn3: Print Name" << endl;
cin >> input;
try {
choice = stoi(input);
if (choice > 0 && choice < 4) {
break;
}
} catch (const std::exception& e) {
}
cout << "Invalid input" << endl;
}
cout << "Your valid choice: " << choice << endl;
}
相关文章:
- 正在尝试了解输入验证循环
- 如何在C++中检查2D数组中负值的输入验证
- cin 的十进制输入验证?
- 输入验证以筛选出字符、字符串和一系列整数
- 输入验证将数字放入向量中
- 在C++中使用字符数组进行输入验证
- 在C++中使用字符数组进行用户输入验证
- C++ 中字符数组的输入验证
- 检查节点的输入验证的整数
- 如何让我的程序在输入验证的基础上读取素数
- C++ 用户输入验证无法正常工作
- 程序终止,而不是继续整数输入验证循环
- 使用REGEX进行电子邮件输入验证C
- C++:输入验证器函数
- 将用户输入验证为整数:用户必须两次输入输入
- C 输入验证
- C :对输入验证函数进行编程的性能影响可以对其进行编程,而每次都可以将其编程
- 使用模板函数进行通用输入验证
- 为什么用于输入验证的 while 循环要么完全跳过循环,要么不考虑错误的输入
- 仅 C++ 字母和空格输入验证