The problem is that the streaming-input operator >>
will try to only read input valid for the type you are inputting to:
int i;
std::cin >> i;
will only read integer values. When this fails, it sets a flag that can be tested for with std::cin::fail()
int i;
std::cin >> i;
if (cin.fail())
throw std::invalid_argument("Expected an int, got some other junk");
However that leaves the input in the input stream, leaving you to use one of various mechanisms to get around it.
What might be easiest is to use std::getline
to read the input line-at-a-time.
#include <string>
#include <iostream>
#include <cctype>
#include <cstdlib>
int main() {
std::string input;
int i = 0;
while (std::cin.good()) {
std::cout << "Enter a number between 3 and 25: ";
std::getline(std::cin, input);
if (input.empty()) // blank lines
continue;
if (isdigit(input[0])) {
i = atoi(input.c_str());
if (i < 3 || i > 25) {
std::cout << "Invalid number, " << input << '\n';
continue;
}
// valid input, stop the loop
break;
}
std::cout << "Unrecognized/non-numeric input: \"" << input << "\"\n";
}
if (i == 0) // we left the loop because cin.good() was false
return 0;
std::cout << "You entered " << i << '\n';
}
Live demo: http://ideone.com/KRHM3V