Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

String to int

Status
Not open for further replies.

pegazaus

Instructor
Aug 16, 2005
22
SE
Is there a way to convert a string (class string) to int in c++, Other than atoi()? I mean is there a function writen, specially for C++, that does that?
 
None that I know of, and more's the pity. If you were using VCL/CLX, you could use AnsiString::ToInt().
 
Hmmmm. I know that in BCB AnsiString does. I haven't used the STL strings in a while so I don't remember.



James P. Cottingham
-----------------------------------------
[sup]I'm number 1,229!
I'm number 1,229![/sup]
 
There is a C++ way:
[tt]
#include <sstream>
std::string s="123";
int i;
(std::istringstream)s >> i;
[/tt]
But it's not as convenient (nor as fast, presumably) as atoi.
 
I thought about the string streams and I've used them to take an int to a string. I never thought about doing it the other way around. :)


James P. Cottingham
-----------------------------------------
[sup]I'm number 1,229!
I'm number 1,229![/sup]
 
AnsiString myString = "123";
int myInteger;

myInteger = myString.ToInt();
or
myInteger = StrToInt(myString);

I suggest you use a try catch clause to prevent a failure.

 
or use:

myInteger = myString.ToIntDef(-1);
or
myInteger = StrToIntDef(myString, -1);

to supply a default value (in this case -1) in the case of an invalid string.
 
Boost's ( [tt]lexical_cast[/tt] function template takes the stringstream technique and encapsulates it into an easy-to-use package that works as you'd expect for anything that has sensible << and >> operators.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top