Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

int to char array?

Status
Not open for further replies.

blackeyrichards

Programmer
Feb 18, 2001
2
GB
This is (hopefully) just a quicky. How do I convert an int to a character array?

I.E., I want to write a correct/working version of this:

int numI = 34;
char numA[255] = (char[255]) numI;

cout<<numA;

Gives the output:34

Thanks,
Paul
 
well I didn't try it but the algorthm should be something like that I think (I'm not very fanous with the C math functions so there should be a better way):

#include <stdio.h>

main()
{
int tmp,numI,i,j;
char *numA;

tmp=numI=12345;
i=j=0;
while (tmp>=1)
{
i++;tmp=(int)tmp/10;
}
numA=(char *)malloc(sizeof(char)*i);
for(j=0;j<i;j++)
{
tmp=(int)numI/10;
tmp=numI-10*tmp;
numI=(int)numI/10;
numA[i-j-1]=(char)tmp+48;
}
printf(&quot;string -> &quot;);
for(j=0;j<i;j++)
{
printf(&quot;%c&quot;,numA[j]);
}
printf(&quot;\n&quot;);
}
 
uups excuse me ;) you can just replace this:

printf(&quot;string -> &quot;);
for(j=0;j<i;j++)
{
printf(&quot;%c&quot;,numA[j]);
}
printf(&quot;\n&quot;);

with this:
printf(&quot;string -> %s\n&quot;,numA);

sorry about that ;)
 
just one line:
sprintf(numA,&quot;%d&quot;,numI);
that is it.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top