int/char to string

Suppose I have an int int d and I want to convert it into a string. How can I do that?

Same question for if d is a char.
Well, the char one is easy:
1
2
3
string lol;
char silly = 'h';
lol+=silly;

Sadly, int is more difficult. I've done it but it involves muchos division. I'll get you started though:
1
2
3
4
5
6
7
8
int chiffre=12345;
string nombre;
int count=chiffre;
while (count>0)
{
//you'll have to use division to get the "ten thousands" and so on...
//don't forget to divide the number by 10 every time
}

I don't want to give away the answer since I found it fun to figure out.

Pelletti
Hello, nguyentrang.
First of all , you must include the sstream header : #include <sstream>
Declare a string : std::string s;
Than, declare an object of type stringstream : std::stringstream out;
Copy the content of d into out : out << d;
Finally, copy the content of out into s : s = out.str();
You now have in s the conversion of the integer d to a string.
You could also use a stringstream. For example;

1
2
3
4
5
6
#include <sstream> // stringstream header.

int val = 20;
stringstream mysstr;
mysstr << val;
return mysstr.str(); // returns "20".  


Edit: Whoops, late.
Last edited on
Hi,

atoi function:Convert string to integer (function) //int atoi ( const char * str );

itoa function:Convert integer to string (non-standard function) //char * itoa ( int value, char * str, int base );



Last edited on
Or you could use sprintf. There are many ways to do it.
1
2
3
int i=123;
char s[12]="";
sprintf(s,"%d",i);

Ofc it depends on whether you mean a c string or a string object. There really should be a constructor like string(int).
Last edited on
Topic archived. No new replies allowed.