Found this on the net:widgetman said:I mean an int. i need to use it as a c string and i wont be printing it out at all. is there a way to do something like cocoa's [NSString stringWithFormat:] and just use %i for the ints?
char * intToString(int num)
{
int i=0;
int j=0;
int k=0;
int ones=0;
char temp[5]; //5=num digits in 32676
char ans[5];
while (num!=0)
{
ones=num%10; //get current ones digit
temp[i]=(char)(ones+48); //48=(int)'0';
num=num/10; //remove current ones digit
i++; //length of number
}
for(j=i-1;j>=0;j--)
{
ans[k]=temp[j]; //reorder string correctly
k++;
}
ans[i]='\0'; //add null char for end of string
return (char *)ans;
}
int myint ;
char mystringbuffer[20] ;
snprintf(mystringbuffer,sizeof(mystringbuffer),"%d",myint) ;
Doctor Q said:Would this work, using the standard C library?
Code:int myint ; char mystringbuffer[20] ; snprintf(mystringbuffer,sizeof(mystringbuffer),"%d",myint) ;
Mitthrawnuruodo said:Found this on the net:..but there is a method, I just got to remember what it was called... (it's been a couple of years since I programmed much in c... )Code:char * intToString(int num) { int i=0; int j=0; int k=0; int ones=0; char temp[5]; //5=num digits in 32676 char ans[5]; while (num!=0) { ones=num%10; //get current ones digit temp[i]=(char)(ones+48); //48=(int)'0'; num=num/10; //remove current ones digit i++; //length of number } for(j=i-1;j>=0;j--) { ans[k]=temp[j]; //reorder string correctly k++; } ans[i]='\0'; //add null char for end of string return (char *)ans; }
int num;
char myBuf[20];
sprintf(myBuf, "%i\0", num);
Mitthrawnuruodo said:I'm so stupid (forgive me, its 2:30AM, here...) EDIT: And I see this has been pointed out already...
You can of course use sprintf()...
Code:int num; char myBuf[20]; sprintf(myBuf, "%i\0", num);
And when you have it in a char buffer, getting it into a string should be easy, right...
Yes, I know sprintf() does this for me, but if I've learned one thing from my C/C++ days, it's that it never hurts to terminate the strings manually, too...hcuar said:You don't need the \0 in the format... sprintf automatically adds the null termination...
BTW... not stupid... just took the long way around.