Possible Duplicate:
How to parse a string to an int in C++?
There are numerous ways to convert string to int in C++03. The best I have found so far is this:
string text;
cin>>text;
int converted;
if ( !(istringstream(text) >> converted) ){
cout<<"conversion failed\n";
}
cout<<"the converted string is "<<converted;
The problem with this solution is that it accepts "12monkeys" and converts it to 12 without hesitation. Is there some simple way to check this and output "conversion failed" in this case?
Just to note I have tried atoi(),atol() and strtol() but the fact that it returns 0 if it fails is futile. How am I supposed to know if the string was not "0"? There is no range check as well (except strtol()). Not mentioning the "12monkeys" problem is present there as well.