C++ 输入检查

标签 c++ input

我有这段代码,它会进行输入检查。它工作到某个时候,但是当我输入例如应该无效的“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
}

关于C++ 输入检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37274380/

相关文章:

c - 如何在 C 中解析输入?

c++ - 当对象的指针存储在 vector 中时,如何访问对象中的方法?

c++ - 在 C++ Eclipse 中未定义对(错误)的引用,但在 Visual Studio 2015 中工作

c++ - 检查 1/n 小数点后是否有无限位数

c++ - 拼接图片检测不到共同特征点

reactjs - 如何找到用户何时停止输入受控组件?

javascript - jquery input.focus+wrap 无法输入输入

c++:如何安全地将 const double** 转换为 const void**

javascript - 有什么方法可以控制数字输入的增量事件,或者让两个数字输入一起工作吗?

c++ - GetKeyState() 与 GetAsyncKeyState() 与 getch()?