Advertisement

String to Int

Started by March 25, 2001 08:30 AM
2 comments, last by Zredna 23 years, 10 months ago
Does anyone know of an C++ function that can convert and string to int like int tal=Str2Int("123"); I have looked in the some of the standard headerfiles and I could find a function that could do this. Also in need an function to do it the other way like char tal[]=Int2Str(123); Anyone know if I need to make the functions myself or if I can find them in the standard lib. i know printf can convert int to strings so I think that atleast the last function is to find in the standard lib. Thanks Zredna
All you others correct me if I am wrong but I think this solves uyour problem:
int atoi( const char *string );
atoi converts your string to an int. And the other way around:
char * itoa( int value, char *string, int radix );
Radix is the base of the value. If you want the value in ordinary numbers you specify 10 as the base or radix, if you want it in hex then you specify the base to 16 and if you want it in binary numbers you specify the base(radix) as 2.
I think I''m correct and these are both in the MSDN.
In the MSDN the itoa function is spelled like _itoa, but I think it works as itoa.
Hope I helped!

---------------------------------------------
These are not the droids you''re looking for
---------------------------------------------
---------------------------------------------These are not the droids you're looking for---------------------------------------------
Advertisement
Use itoa() to convert int to string (itoa is short for "i nt to a scii"). Use atoi() to convert from string to int.

There are a lot more functions for different datatypes, like ltoa() (for long), ultoa() (for unsigned long), etc etc. Check out your documentation, they''re all there.

Harry.
Harry.
Or you use string stream instead :

            #include <sstream>#include <string>int main(){    std::String numberstring( "44 66 42" );    std::istringstream inStream;    inStream.str( numberstring ); //set the string buffer    int i,j,k;    inStream >> i; //i contains 44!!!    inStream >> k; //k contains 66!    inStream >> j; //j contains 42!    std::osstringstream os;    os << k;  //os now contains "66"    os << " " << j;    os << " " << i;  //os is now "66 42 44"    std::String newnumberstring = os.str(); //get the string buffer}  


If you want to clear the buffer, you write stream.str("");

There are also string streams that uses char* instead.

simply include strstream and use istrstream and ostrstream instead.

you must not forget to put the \0 at the end of and ouput strstream.


  std::ostrstream os;os << "hello" << " world" << std::ends;    //ends is \0      







Edited by - Gorg on March 25, 2001 12:08:57 PM

This topic is closed to new replies.

Advertisement