What is effective, itoa or sprintf?

I participate in the processes of creating my first C ++ application and choosing the effective C ++ libraries you can rely on at this stage - this is one of the design considerations that I look at.

Therefore, I want to convert the integer type to a string and decide whether to use it;

sprintf(string, "%d", x);

or

Integer for ASCI

itoa(x, string);

Can anyone suggest which of these routes is effective and maybe why?

Thank.

+5
source share
3 answers

Do not use any of them. Use std::stringstreametc.

std::stringstream ss;
ss << x;
ss.str();  // Access the std::string

In any case, it is unlikely that conversion to string will be a significant part of the runtime of your application.

+10
source

. , , itoa() ++ , , . ( , libstdc++, Mac OS X Linux.)

+14

, itoa , sprintf . , , .

, . sprintf , itoa, , , .

Additionally: If you can use C ++ 11, you can use to_stringone that returns to you std::string. If you need representations other than decimal, you can do this:

int i = 1234;
std::stringstream ss;
ss << std::hex << i;       // hexadecimal
ss << std::oct << i;       // octal
ss << std::dec << i;       // decimal

std::bitset<sizeof(int) * std::numeric_limits<unsigned char>::digits> b(i);
ss << b;                   // binary

std::string str = ss.str();
0
source

All Articles