I’m writing a template function that will check if the user has assigned the correct type of data that the answer should be in. For example:
int main(){
int E;
cout<<"Enter an integer: "<<endl;
E = clear_and_read<int>(cin);
cout<<E<<endl;
}
where the function clear_and_read is defined as:
template <class T> T clear_and_read(istream& inputstream){
cin.sync();//removes anything still in cin stream
cin.clear();
T input;
inputstream>>input;
while(inputstream.fail()){
cout<<endl<<"Please ensure you are inputting correct data type. Suggested data type: "<< typeid(input).name() <<"."<<endl;
cin.sync();
cin.clear();
inputstream>>input;
}
return input;
}
Now this works if I try to enter a string instead of an integer, but when I enter a double it just assigns it’s first value. e.g. 5.678 becomes 5.
What can I do inside the template function to flag if a double is being read into an int?
I’d try a slightly different take than you have. Specifically, I would not try to modify the error state of the input stream:
Note: If you don’t have boost available in your compilation environment,
lexical_castis fairly trivial to implement yourself. If you get stuck, just ask for help.References:
EDIT Here is a fully tested version, that does not rely upon Boost.