I've tried this.
Code:
#include <sstream>
#include <iostream>
using namespace std;
bool isint( const string& s ) {
stringstream str;
string srest;
int i;
str << s;
str >> i;
str >> srest;
if ( srest.length() > 0 )
return false;
str.str("");
str.clear();
str << i;
return str.str() == s;
}
int main() {
string str("12ad34");
if ( isint( str ) )
cout << str << " is an int" << endl;
else
cout << str << " is not an int" << endl;
str = "123456899999999";
if ( isint( str ) )
cout << str << " is an int" << endl;
else
cout << str << " is not an int" << endl;
str = "123459";
if ( isint( str ) )
cout << str << " is an int" << endl;
else
cout << str << " is not an int" << endl;
}
Without that second check in isint() overflow would not be detected. ( I'm using g++ 3.3.5 )
Kurt