How to accept a string and an int using cin?

This is one of the few cases where I’d say a regex is by far your best solution.

You could use a regex like:

^\s*([a-zA-Z]+)\s*(\d+)\s*$

Then use regex_match to check it. So for an input string foo:

smatch bar;

if(regex_match(foo, bar, regex{"^\\s*([a-zA-Z]+)\\s*(\\d+)\\s*$"})) {
    cout << "OK: " << bar[1] << '\t' << bar[2] << endl;
} else {
    cout << "not OK\n";
}

Live Example

Leave a Comment