Int To String

Hi, i am beginner.
How to convect int to string? :p

you need separate int into number, then you assign every string equal every number, after reverse their
ex: 123 is 1 , 2 and 3
123 % 10 is 3
123 / 10 is 12
12 % 10 is 2
12 / 10 is 1
1 % 10 is 1
1 / 10 is 0
You could use streams:

1
2
3
4
5
int i = 10;
std::stringstream ss;
ss<< i;
std::string s = ss.str();
std::cout<< s<< '\n';


You could also use std::to_string() (which is new to C++11):

1
2
int j = 10;
std::string str = std::to_string(j);


http://www.cplusplus.com/reference/string/to_string/
that's so easy man
ButchCavendish wrote:
that's so easy man
That was such a helpful comment.

On topic now, I would suggest what Danny Toledo mentioned. If you can't though for some reason you could do what CongoDao said which would be something like
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Example program
#include <iostream>
#include <string>

int main()
{
    int integer = 123456789;
    int temp = integer;
    std::string str = "";
    while(temp) //!= 0
    {
        str += temp % 10 + '0';
        temp /= 10;
    }
    
    str = std::string(str.rbegin(), str.rend()); //reverse it
    std::cout << "Integer: " << integer << '\n';
    std::cout << "String: " << str << std::endl;
}
123456789
123456789


I would suggest the other methods (stringstream or to_string) since they are more efficient though.
OP, note that if you just want to print the integer, the streams library will do that for you:
1
2
int i = 12345;
cout << i;


If you have to write your own, be careful about handling negative numbers and zero.
Topic archived. No new replies allowed.