Given a string that should represent a number, I\'d like to put it into a conversion function which would provide notification if the whole string did not convert.<
Alternatively you can use std::istringstream
as you mentioned, but check to make sure it parsed to the end of the stream. Assuming you have a constant reference, you could do something like the following
T parse(const std::string& input) {
std::istringstream iss(input);
T result;
iss >> result;
if (iss.eof() || iss.tellg() == int(input.size())) {
return result;
} else {
throw std::invalid_argument("Couldn't parse entire string");
}
}
The benefit of this approach is that you parse anything that overloads operator>>
. Note: I'm not entirely sure if the condition is enough, but with my testing it seemed to be. For some reason the stream would get a failure marking if it parsed to the end.