@OP or a more generic approach:
struct InvalidInputException : std::exception{
InvalidInputException(): std::exception("Error: Invalid conversion") {}
};
//tries to get a data of type T, throws InvalidInputException if failed
template<typename T>
T prompt(const std::string msg){
cout << msg ;
T res = T();
if( ! (cin >> res) ){
cin.clear();
while(cin.get() != '\n' ) continue;
throw InvalidInputException();
}
else return res;
}
int main(){
try{
int age = prompt("What is your age? ");
string name = prompt("What is your name? ");
}catch(std::exception& e){ cout << "whyyyyyyy?\n"; }
}
@psuedorandom: I like that solution but some things,
1) The name int_type is misleading since the user can use that function to get a string for example.
2) I don't like the performance issue with writing just one input to a file everytime that function is called, I would rather do lazy write and write only when necessary.
and I guess whether the function should throw exception on failed input is a matter of choice.