且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C ++中验证用户输入是双重的?

更新时间:2023-11-26 11:03:34

尝试:

while (1) {
  if (cin >> x) {
      // valid number
      break;
  } else {
      // not a valid number
      cout << "Invalid Input! Please input a numerical value." << endl;
      cin.clear();
      while (cin.get() != '\n') ; // empty loop
  }
}



这基本上清除错误状态,然后读取并丢弃在上一行输入的所有内容。

This basically clears the error state, then reads and discards everything that was entered on the previous line.