Operating System - HP-UX
1836748 Members
2811 Online
110109 Solutions
New Discussion

Convert an integer to a string

 
SOLVED
Go to solution
Sathish C
Frequent Advisor

Convert an integer to a string

Hi
Is there any easy way to convert an integer value to a string in C under Unix .

Ex

int number=123;
char strnum[4];
strcpy(strnum,to_string(number));

where to_string will have to give me the integer to string .
Some cause happiness wherever they go; others, whenever they go
2 REPLIES 2
harry d brown jr
Honored Contributor

Re: Convert an integer to a string

sprintf

live free or die
harry
Live Free or Die
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: Convert an integer to a string

int number = 123;
char strnum[16];
(void) sprintf(strnum,"%d",number);

/* You can also use a format specifier to
produce a fixed format; it's always a good idea to oversize the destination string because this is C and if your put 1,000,000 into a 4 character string, sprintf will dutifully carry out your commands and corrupt surrounding data */

/* This will produce a zero-padded 6 character output 8/
(void) sprintf(strnum,"%06d",number);
(void) printf("My number is %s\n",strnum);
If it ain't broke, I can fix that.