0

example:

string id;
cout << "Enter the ID: ";
cin >> id;

The format must be like this UEEW123456, which contain 4 characters in front and 6 integers at back. How can I validate and make sure the input follow this format and prompt user to enter again if he/she did not follow this format.

Nino
  • 11
  • 3
  • You could use `std::isalpha` and `std::isdigit` – Galik Aug 18 '21 at 11:20
  • Or you could use the [regex library from C++11](https://en.cppreference.com/w/cpp/regex) combined with a simple input validation loop, like in [this question](https://stackoverflow.com/questions/2075898/good-input-validation-loop-using-cin-c) – Lukas-T Aug 18 '21 at 11:22

1 Answers1

1

You can use regular expressions for this.

#include <cassert>
#include <string>
#include <regex>

bool is_valid(const std::string& input)
{
    static std::regex expression{ "[A-Z]{4}[0-9]{6}" };
    std::cmatch match;
    return std::regex_match(input.c_str(), match, expression);
}

int main()
{
    assert(is_valid("UEEW123456"));
    assert(!is_valid("123456UEEW"));
    assert(!is_valid("UEEW12345Z"));
}
Pepijn Kramer
  • 9,356
  • 2
  • 8
  • 19