C++输入检查

C++ input check

本文关键字:检查 输入 C++      更新时间:2023-10-16

我有这段代码,它会进行输入检查。它一直工作到某个时候,但当我输入例如"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"