I am looking for a method to convert a string represent of an integer (say, "123") to an integer in C++03.
I am aware about the usual method of using stringstreams
:
string token="1234";
stringstream sss(token);
int tokenInt;
sss>>tokenInt;
cout<<"Int token is: "<<tokenInt<<"\n";
However, the problem with this is that it doesn't appear to work on values like 1e1
. It just prints out 1
. Working demo here . stoi
is unfortunately ruled out since I am using C++0x. Any other way?
Thanks!
Edit: I am basically working on IPv4 and IPv6 addresses. The function ipValidator()
returns valid if it is a valid IPv4 or IPv6 address. I split the input, say, 1e1.4.5.6
into tokens 1e1
, 4
, 5
and 6
. Since, 1e1
is incorrect, I need to return false. Unfortunately, the above method returns true
since it process 1e1
as just a 1
.
You're almost there. After you do the conversion you need to check if there is any data left in the stream. If there is then you know you had invalid input. So if
the_stream.eof()
is true
then you consumed on the input and you have a valid result. If not then you have invalid input.
You can use C function strtol
as well:
std::string token = "1234";
char *endp = 0;
int value = strtol( token.c_str(), &endp, 10 );
if( **endp ) { // invalid symbol detected
...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.