🔒 Locked
integer --> string
Advertisement
Original Post
atoi() converts alpha to integer
itoa() converts integer to alpha..
anybody see a pattern emerging?
-eldee
;another space monkey;
[ Forced Evolution Studios ]
itoa() converts integer to alpha..
anybody see a pattern emerging?
-eldee
;another space monkey;
[ Forced Evolution Studios ]
In C++ you can make an istringstream passing the string as a parameter and read an int from it as if it was reading from cin or a file.
[ MSVC Fixes | STL | SDL | Game AI | Sockets | C++ Faq Lite | Boost | Asking Questions ]
[ MSVC Fixes | STL | SDL | Game AI | Sockets | C++ Faq Lite | Boost | Asking Questions ]
quote:
Original post by BeerNutts
Number = 0;
for(i = 0; i < strlen(String); i++)
{
Number += (i * 10) + (String[(strlen(String) - 1) - i] - ''0'');
}
da, that''s (close to) the standard procedure
cut down on a few function calls and some arithmatic
len = strlen(string) - 1;
for(i = 0; i <= len; i++)
{
number += pow(10, i) * (string[i] - ''0'');
}
Or work the string in reverse and * 10 to a multiplier every time
len = strlen(string) - 1;
for(i = len, mul = 1; i >= 0; i--, mul *= 10)
{
number += mul * string[i] - ''0'';
}
This is of course if you assume that everything is honky dory in the input.
Or you can just use the istringstream or atoi built in functions
-Warden
Use boost::lexical_cast
See sig for link.
[Questions (STFW) | GDNet Start Here | GDNet Search | Forum FAQ | Google | Asking Smart Questions ]
[Docs (RTFM) | MSDN | SGI''s STL | OpenGL | File formats]
[C++ Must Haves (RTFS) | MinGW | Boost | Loki | FLTK | SDL ]
Stolen from Magmai Kai Holmlor, who held it from Oluseyi, who was inspired by Kylotan...
See sig for link.
[Questions (STFW) | GDNet Start Here | GDNet Search | Forum FAQ | Google | Asking Smart Questions ]
[Docs (RTFM) | MSDN | SGI''s STL | OpenGL | File formats]
[C++ Must Haves (RTFS) | MinGW | Boost | Loki | FLTK | SDL ]
Stolen from Magmai Kai Holmlor, who held it from Oluseyi, who was inspired by Kylotan...
You could also use sprintf() instead of coding up an algorithm to convert.
Now you have "2345" as a string. This also makes it easy to convert to Hex. Use %x instead.
For any other base though, you''ll have to do the conversion manually.
char value[256];
int number = 2345;
sprintf(value, "%d", number);
Now you have "2345" as a string. This also makes it easy to convert to Hex. Use %x instead.
For any other base though, you''ll have to do the conversion manually.
Topic Locked
This topic has been locked by a moderator. New replies are not allowed.
Sign in to reply to this topic.
Advertisement
