C++输入检查
C++ input check
我有这段代码,它会进行输入检查。它一直工作到某个时候,但当我输入例如"12rc"时,它被认为是无效的,检查被跳过。我该怎么改?提前谢谢!
cout << "Enter your choice 1, 2, 3: ";
cin >> choice;
cout << endl;
while (cin.fail() || choice <=0 || choice >=4) { // check input value
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
cout << "Wrong input value! Please enter only 1, 2, 3: ";
cin >> choice;
cout << endl;
我假设您希望从标准输入流中获得一个整数。在其他情况下,你可能会有同样的想法,并意识到如何概括你的问题。我认为它可能会像这个一样以某种方式解决
#include <iostream>
#include <cctype>
#include <stdexcept>
void skip_to_int() {
if (std::cin.fail()) {
// try to fix up a mess in the input
std::cin.clear();
for (char ch; std::cin >> ch; ) {
if (std::isdigit(ch) || ch == '-') {
std::cin.unget()
return;
}
}
}
// throw an error for example
throw std::invalid_argument{"Not integral input"};
}
int get_int() {
int n;
// try to get the integer number
while (true) {
if (std::cin >> n) {
return n;
}
std::cout << "Sorry, that was not a number. Try again" << std::endl;
// if user inputed not an integral try to search through stream for
// int occurence
skip_to_int();
}
}
int main() {
std::cout << "Enter your choice 1, 2, 3: " << std::endl;
int choice = get_int();
while (choice <= 0 && choice >= 3) {
// continue searching
choice = get_int();
}
// process choice somehow
}
您的代码没有任何问题。它适用于"12rc"这样的输入:http://ideone.com/Ma0j7r
The inputs:
12rc
0
a
11
$
10
2
收益率:
输入您的选择1、2、3:
输入值错误!请仅输入1、2、3:
输入值错误!请仅输入1、2、3:
输入值错误!请仅输入1、2、3:
输入值错误!请仅输入1、2、3:
输入值错误!请仅输入1、2、3:
输入值错误!请只输入1、2、3:
你可能在"2rc"之前有空位吗?这些输入将被读取为1:
- "1 2rc"
- "1rc"
- \n1\nrc"
相关文章:
- 检查输入是否不是整数或数字
- 检查输入 std::array 指针数据是否等于某个常量数组
- 如何检查输入是否有效?
- 为什么复制构造函数不需要检查输入对象是否指向自身?
- 我已经创建了一个模板函数,但是在检查输入是奇数还是偶数时收到错误 C++.
- 如果是数字或字符,请检查输入
- 尝试检查输入的文本与我自己的自定义答案
- 如何检查输入是否为字符并显示它是"invalid input",否则它将按原样运行
- 检查输入是否为字母数字时的逻辑错误
- 如何检查输入缓冲区是否为空
- 检查输入通信是否正确
- 如何检查输入文件是否已更新
- C++:检查输入数据
- 功能调用,该函数从文本文件-C 检查输入正确性
- 如何检查输入是整数,字符串还是浮动在C 中
- 检查输入是否为数字,否则将其视为字符
- 如何在牡丹加密中检查输入的密码是否正确
- 检查输入的文件是否有任何错误
- 检查输入值是整数类型
- 如何检查输入是否为整数/字符串