Umedh Singh Bundela Umedh Singh Bundela - 1 year ago 62
C++ Question

Converting a std::string to int in C++03

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
.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download