Ahmed_Hussein_Karam's blog

By Ahmed_Hussein_Karam, history, 9 years ago, In English

What is the most efficient way to convert an integer to a string in C++?

| Write comment?
»
9 years ago, # |
Rev. 4   Vote: I like it +3 Vote: I do not like it

add this library #include <sstream>
and then write this function

string convert (int x){
    ostringstream temp;
    temp << x;
    return temp.str();
}

Or just use s = to_string(x); where s is string, x is integer

»
9 years ago, # |
  Vote: I like it +12 Vote: I do not like it

I like to use sprintf() for this kind of situation.

char buf[100];
int x = 10123;
sprintf ( buf, "%d", x );

buf[] has the value of x in it as string. It's like printf() function, but for strings. Hence the name sprintf().

And yes, we also have sscanf().

char buf[] = "1235";
int x;
sscanf ( buf, "%d", &x);