Skip to main content
GameDev.net gamedev.net
🔒 Locked

converting an int to a string

Started by CJWR Jul 9, 2005 at 3:04 PM 22 replies 5.9k views
Original Post
CJWR
CJWR
is there any function to do this? i'd rather not have to write my own lol.
Charles Reed, CEO of CJWR Software LLC
SiCrane
SiCrane
Assuming C++, since that seems to be what you've used in your other posts, you can either use boost::lexical_cast or a std::stringstream.
std::stringstream sstr;sstr << my_int;std::string str1 = sstr.str();std::string str2 = boost::lexical_cast<std::string>(my_int);
Gink
Gink
sprintf works.

int sprintf( char *buffer, const char *format, ... );

like so
char buf[5]
int value = 5555;
sprintf(buf,"%i",value);
bytecoder
bytecoder
Quote:
Original post by Gink
sprintf works.

int sprintf( char *buffer, const char *format, ... );

like so
char buf[5]
int value = 5555;
sprintf(buf,"%i",value);

If you're going to use C, you might as well use something like itoa.
SiCrane
SiCrane
If you care about portable code I highly recommend avoiding itoa(). It is severly non-standard. Not only is it not part of the C standard library, but in non-standard implementations I've seen at least five different function signatures for itoa(), with different memory management conventions:
char * itoa(int, char *, int); // you supply the bufferchar * itoa(int, int, char *); // you supply the bufferchar * itoa(int, char *);      // you supply the bufferchar * itoa(int, int);         // you need to free the pointerchar * itoa(int);              // you need to free the pointer
bytecoder
bytecoder
Quote:
Original post by SiCrane
If you care about portable code I highly recommend avoiding itoa(). It is severly non-standard. Not only is it not part of the C standard library, but in non-standard implementations I've seen at least five different function signatures for itoa(), with different memory management conventions:
char * itoa(int, char *, int); // you supply the bufferchar * itoa(int, int, char *); // you supply the bufferchar * itoa(int, char *);      // you supply the bufferchar * itoa(int, int);         // you need to free the pointerchar * itoa(int);              // you need to free the pointer

Hmm, didn't know that. Nevermind, then.
CJWR
CJWR
alright, for anyone who cares about this at all, here is my little function to convert a int to a string. on vc++ 6, this works up to 999,999,999. It doesn't do any formating or anything, but all my tests show it works just fine. let me know if you see any problems with it.

string int_to_string(int num){	//cout << "number inputed = " << num << endl;	int num_size = 0; //holds the size of the number	string str; //holds the actual string we will return	//find out how large the number is	int temp = num/10; //used to find how large the number is	num_size++;	while(temp != 0){		temp = temp / 10;		num_size++;	}	//cout << "num size = " << num_size << endl;	int one_place = 0;	int div = 10; //holds the number num should be divided by	for(int i = 0; i < num_size-2; i++){		div = div * 10;	}	//cout << "div = " << div << endl << endl;		for(i = num_size; i > 0; i--){		one_place = num/div;		//add this number to the string		if(one_place == 1){			str = str + "1";		}		else if(one_place == 2){			str = str + "2";		}		else if(one_place == 3){			str = str + "3";		}		else if(one_place == 4){			str = str + "4";		}		else if(one_place == 5){			str = str + "5";		}		else if(one_place == 6){			str = str + "6";		}		else if(one_place == 7){			str = str + "7";		}		else if(one_place == 8){			str = str + "8";		}		else if(one_place == 9){			str = str + "9";		}		else{			str = str + "0";		}		//find what remains of the number		num = num - (div*one_place);		//set up div for the next pass		div = div / 10;		//output info (for testing only)		//cout << "This pass info" << endl;		//cout << "div = " << div << endl;		//cout << "num = " << num << endl;		//cout << "one_place = " << one_place << endl;	}	return str;}
Charles Reed, CEO of CJWR Software LLC
Fruny
Fruny
Quote:
Original post by CJWR
alright, for anyone who cares about this at all, here is my little function to convert a int to a string. on vc++ 6, this works up to 999,999,999. It doesn't do any formating or anything, but all my tests show it works just fine. let me know if you see any problems with it.


Well, it doesn't work with negative numbers, for starters. And, well, SiCrane told you how to do it, why not use what he said?
"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
CJWR
CJWR
Quote:
Original post by Fruny
Quote:
Original post by CJWR
alright, for anyone who cares about this at all, here is my little function to convert a int to a string. on vc++ 6, this works up to 999,999,999. It doesn't do any formating or anything, but all my tests show it works just fine. let me know if you see any problems with it.


Well, it doesn't work with negative numbers, for starters. And, well, SiCrane told you how to do it, why not use what he said?


i wanted to write my own lol, but the negative thing isn't a problem for what i need this for. but it is something to work on later. :)
Charles Reed, CEO of CJWR Software LLC
smart_idiot
smart_idiot
Turn stuff into strings, free with your purchase of 1 or more immortality rings.

#include <sstream>#include <string>template <typename T> std::string toString(const T &value) {  std::stringstream stream;  stream << value;  return stream.str(); }
Chess is played by three people. Two people play the game; the third provides moral support for the pawns. The object of the game is to kill your opponent by flinging captured pieces at his head. Since the only piece that can be killed is a pawn, the two armies agree to meet in a pawn-infested area (or even a pawn shop) and kill as many pawns as possible in the crossfire. If the game goes on for an hour, one player may legally attempt to gouge out the other
CJWR
CJWR
Quote:
Original post by smart_idiot
Turn stuff into strings, free with your purchase of 1 or more immortality rings.

*** Source Snippet Removed ***


that dude is a fruitcake lol. not you, the guy that owns that site.
Charles Reed, CEO of CJWR Software LLC
CJWR
CJWR
Quote:
Original post by zealotgi
Wholly crap people. They guy is looking for a simple way to do this, not template rocket science!!!

Use sprintf()


well, i'm happy with my little function, it does all i need to do. and it allows me to get back to creating my game :).
Charles Reed, CEO of CJWR Software LLC
CJWR
CJWR
and here is a version that works with negatives as well.

string int_to_string(int num){	//cout << "number inputed = " << num << endl;	int num_size = 0; //holds the size of the number	string str; //holds the actual string we will return	//first check if the number is negative (less than 0)	if(num < 0){		num = (-num);		str = str + '-';	}	else;	//find out how large the number is	int temp = num/10; //used to find how large the number is	num_size++;	while(temp != 0){		temp = temp / 10;		num_size++;	}	//cout << "num size = " << num_size << endl;	int one_place = 0;	int div = 1; //holds the number num should be divided by	for(int i = 0; i < num_size-1; i++){		div = div * 10;	}	//cout << "div = " << div << endl << endl;		for(i = num_size; i > 0; i--){		one_place = num/div;		//add this number to the string		if(one_place == 1){			str = str + "1";		}		else if(one_place == 2){			str = str + "2";		}		else if(one_place == 3){			str = str + "3";		}		else if(one_place == 4){			str = str + "4";		}		else if(one_place == 5){			str = str + "5";		}		else if(one_place == 6){			str = str + "6";		}		else if(one_place == 7){			str = str + "7";		}		else if(one_place == 8){			str = str + "8";		}		else if(one_place == 9){			str = str + "9";		}		else{			str = str + "0";		}		//find what remains of the number		num = num - (div*one_place);		//set up div for the next pass		div = div / 10;		//output info (for testing only)		//cout << "This pass info" << endl;		//cout << "div = " << div << endl;		//cout << "num = " << num << endl;		//cout << "one_place = " << one_place << endl;	}	return str;}


i know this is sort of reinventing the wheel, but it was an interesting little hour project.
Charles Reed, CEO of CJWR Software LLC
smart_idiot
smart_idiot
How about instead of all those if statements, you use str += static_cast('0'+one_place)?

Edit: Seems to need a cast to work right.
Chess is played by three people. Two people play the game; the third provides moral support for the pawns. The object of the game is to kill your opponent by flinging captured pieces at his head. Since the only piece that can be killed is a pawn, the two armies agree to meet in a pawn-infested area (or even a pawn shop) and kill as many pawns as possible in the crossfire. If the game goes on for an hour, one player may legally attempt to gouge out the other
CJWR
CJWR
Quote:
Original post by smart_idiot
How about instead of all those if statements, you use str += static_cast('0'+one_place)?

Edit: Seems to need a cast to work right.


well, it did work fine with any number 10 and above (up to however high ints go lol), and i just fixed it so it works on int 1-9 as well. i think it works for any number that fits into an int now. have you found a number that it wouldn't work for?
Charles Reed, CEO of CJWR Software LLC
smart_idiot
smart_idiot
I'm bored, how about I reinvent the wheel, too?

std::string toString(int value) {  char buffer[32] = {0}, *out = buffer+31;    if(!value)   return "0";  else if(value >= 0) for(; value > 0; value /= 10)   *--out = '0'+value%10;  else   {    for(value *= -1; value > 0; value /= 10)     *--out = '0'+value%10;        *--out = '-';   }     return out; }


* head explody *

[Edited by - smart_idiot on July 10, 2005 12:28:40 AM]
Chess is played by three people. Two people play the game; the third provides moral support for the pawns. The object of the game is to kill your opponent by flinging captured pieces at his head. Since the only piece that can be killed is a pawn, the two armies agree to meet in a pawn-infested area (or even a pawn shop) and kill as many pawns as possible in the crossfire. If the game goes on for an hour, one player may legally attempt to gouge out the other
CJWR
CJWR
Quote:
Original post by smart_idiot
I'm bored, how about I reinvent the wheel, too?

*** Source Snippet Removed ***


you win lol. much better than mine. why the heck didn't i think of that?
Charles Reed, CEO of CJWR Software LLC
smart_idiot
smart_idiot
Actually, I think mine would print an empty string for 0. Oopsies.
Chess is played by three people. Two people play the game; the third provides moral support for the pawns. The object of the game is to kill your opponent by flinging captured pieces at his head. Since the only piece that can be killed is a pawn, the two armies agree to meet in a pawn-infested area (or even a pawn shop) and kill as many pawns as possible in the crossfire. If the game goes on for an hour, one player may legally attempt to gouge out the other
Raduprv
Raduprv
Quote:
Original post by bytecoder
If you're going to use C, you might as well use something like itoa.


itoa() is not ANSIC C, so it's not guaranteed that it's implemented on every compiler.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.