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

How to verify all correct input digits C++

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

I have the following code, this can check if the input is an integer; however, if something like '5o' is input it still flows through, can someone help me make sure all the digits input into x are correct, thank you!

#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
0
Ayxan Haqverdili 2020-11-28 17:28:51

Read an entire line at once as a string and validate:

#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);
}