Nino
Nino

Reputation: 11

How can I validate the data in this format UEEW123456

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.

Upvotes: 0

Views: 31

Answers (1)

Pepijn Kramer
Pepijn Kramer

Reputation: 12956

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

Upvotes: 1

Related Questions