Warm tip: This article is reproduced from serverfault.com, please click
c++

其他-如何验证所有正确的输入数字C ++

(其他 - How to verify all correct input digits C++)

发布于 2020-11-28 08:41:47

我有以下代码,可以检查输入是否为整数;但是,如果仍然输入诸如“ 5o”之类的内容,则有人可以帮助我确保输入到x的所有数字都是正确的,谢谢!

#include <iostream>
using namespace std;
int main() {
  cout << "enter x please: ";
  int x;
  cin >> x;
  while (cin.fail()) {
    cout << "sorry wrong input, try again: ";
    cin.clear();
    cin.ignore();
    cin >> x;
  }
  cout << "correct input!";
  return 0;
}
Questioner
harry
Viewed
11
Ayxan Haqverdili 2020-11-28 17:28:51

以字符串形式一次读取整行并验证:

#include <iostream>
#include <string>
#include <algorithm>
#include <cstdio>
#include <cctype>

int main()
{
    std::printf("Enter x: ");
    
    std::string line;

    while (true) 
    {
        if (!std::getline(std::cin, line))
        {
            std::puts("Stream failed."); // Not much we can do
            return -1;
        }

        if (std::all_of(line.cbegin(), line.cend(), std::isdigit))
            break;
        else
            std::printf("Input is not a number. Try again: ");
    }
    int const x = std::stoi(line);
    std::printf("x = %d\n", x);
}