The operator>> immediately parses the input data, you cannot intervene in that. You can, however, scan an entire input line and check for any illegal characters, like this:
std::string str; // scans the entire line std::getline(std::cin, str); // checks for existence of any invalid characters // refer to http://www.cplusplus.com/reference/string/string/find_first_not_of/ if(str.find_first_not_of("0123456789") != std::string::npos) { [handle the error] } // parse the string when you know it is valid else { int result = std::stoi(str); }
EDIT: As suggested in the comments, here is an alternative way that uses the option to retrieve the number of characters parsed from std::stoi.
std::string str; std::size_t sz; int i; std::getline(std::cin, str); try { i = std::stoi(str, &sz); } catch(std::exception) { // failed to parse [handle the error] } if(sz != str.length()) { // parsed, but there are trailing invalid characters [handle the error] } else { // valid input was provided }
getline(). Also, consider using something like Test Driven Development to make sure cases are handled correctly. As a new user here, also take the tour and read How to Ask. BTW: The formatting of your code is a bit messed up, edit your question to fix that.