Skip to main content
gamedev.net
🔒 Locked

integer --> string

Started by Kosov Apr 10, 2002 at 10:12 AM 8 replies 1.7k views
Original Post
Kosov
Kosov
Hello all, i know the function itoa which converte an integer to a string but i need to converte a string to an integer. I''m using C/C++ in an MFC code. Can someone help me ?
BeerNutts
BeerNutts

  
Number = 0;
for(i = 0; i < strlen(String); i++)
{
Number += (i * 10) + (String[(strlen(String) - 1) - i] - ''0'');
}
My Gamedev Journal: 2D Game Making, the Easy Way

---(Old Blog, still has good info): 2dGameMaking
-----
"No one ever posts on that message board; it's too crowded." - Yoga Berra (sorta)
Warden
Warden
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
-Warden
Fruny
Fruny
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...
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Kosov
Kosov
Thx all !!!
I m a little tired and i was sur that the function itoa doesn''t exist.

Well now i know its algorithm ;-)
Kosov
Kosov
Thx all !!!
I m a little tired and i was sur that the function itoa doesn''t exist.

Well now i know its algorithm ;-)
cgoat
cgoat
You could also use sprintf() instead of coding up an algorithm to convert.


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.