Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an integer to a string portably?

I was looking for a way to convert an integer to a string in a portable manner (portable among at least Windows & Linux and x86 and x86_64) and I though itoa(X) to be standard just like atoi(1).

But I read the following in the Wikipedia entry:

The itoa function is a widespread non-standard extension to the standard C programming language. It cannot be portably used, as it is not defined in any of the C language standards; however, compilers often provide it through the header while in non-conforming mode, because it is a logical counterpart to the standard library function atoi.

So I'd like to know if there is any way to do it in a portable manner or not. In case I have to write my own function, which things do I have to be careful with?

like image 614
Dimitri Spirtovic Avatar asked Feb 09 '10 00:02

Dimitri Spirtovic


People also ask

How do I convert an int to a string in C++?

The next method in this list to convert int to string in C++ is by using the to_string() function. This function is used to convert not only the integer but numerical values of any data type into a string. The to_string() method is included in the header file of the class string, i.e., <string> or <cstring>.

Is the easiest way to convert an integer to a string in C?

Solution: Use sprintf() function. You can also write your own function using ASCII values of numbers.


1 Answers

Most often you just use printf("%d");

http://en.wikipedia.org/wiki/Printf

You can use sprintf if you need it in a buffer, but how often do you convert to a string and not write it to a file or output device?

like image 111
Hogan Avatar answered Oct 06 '22 08:10

Hogan