6

I would like to convert an integer to a string like:

int a = 12345

coverts to

char b[6] = "12345"

basically the opposite of the atoi function that converts a string to an integer.

Invisible Hippo
  • 124
  • 1
  • 1
  • 9

3 Answers3

12
#include <stdio.h>
int sprintf(char *str, const char *format, ...);

Example

char str[10]; 
sprintf(str,"%d", 12345);
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
vonzhou
  • 339
  • 1
  • 5
4

source: Here

char * itoa ( int value, char * str, int base )

Convert integer to string (non-standard function) Converts an integer value to a null-terminated string using the specified base and stores the result in the array given by str parameter.

If base is 10 and value is negative, the resulting string is preceded with a minus sign (-). With any other base, value is always considered unsigned.

str should be an array long enough to contain any possible value: (sizeof(int)*8+1) for radix=2, i.e. 17 bytes in 16-bits platforms and 33 in 32-bits platforms.

But is not defined in ANSI-C and is not part of C++

A standard-compliant alternative for some cases may be sprintf:

  • sprintf(str,"%d",value) converts to decimal base.
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
-3

Use itoa(). That should do the trick.(Only some compilers have it)

Heatblast016
  • 8
  • 1
  • 3