Hi,
I have a loop that counts 1 to 25. I want to append the number (I) from the loop to the end a string. I can do it like str[len] = '1', but it I do str[len] = i, I get some kind of weird character. Any ideas? thanks.
Programming
Last Comment
tommydoyle
8/22/2022 - Mon
frogger1999
If this is not homework I will give you an example, but in general look up
//i is the number to convert
//dest is the destination char buffer
//radix is the base of the number (10 for example)
char * itoa(int i, char * dest, int radix)
to convert your int to a string
and then use strcat(char * dest, const char * src)
you will end up with a string with dest+src
good luck.
010101010101
ASKER
frogger1999,
Thanks for the help, unfortunately itoa is not ansi c, and does not work with my compiler (GCC 3.2.1 FreeBSD). I looked in the header files, and could only find referances to atoi (the opposite of what I want). Any other ideas? I tried toascii, but had no success. I also tried to cast the int as a char but that did not work either. Thanks.
010101010101
ASKER
Ok. figured it out. I simply added 48 to the number (ascii table) I wanted, then set strlen = number, then strlen+1 = '\0'. Thanks.
for (i=1 ; i<=25 ; i++)
{
if (i>=10) { /*We have to deal with 2 digits*/
yourstring[slen]= (char)(i/10) + '0'; /*Tens digit*/
yourstring[slen+1]= (char)(i%10) + '0'; /*Ones digit*/
yourstring[slen+2]= '\0'; /*Null terminate string*/
}
else { /*We only have to deal with 1 digit here*/
yourstring[slen]= (char)(i%10) + '0'; /*Ones digit*/
yourstring[slen+1]= '\0';/*Null terminate string*/
}
printf("%s\n",yourstring); /*Print yourstring to screen*/
}
NOTE: You have to be sure that the size of the yourstring character buffer is large enough to hold the extra characters that you are appending at the end.
//i is the number to convert
//dest is the destination char buffer
//radix is the base of the number (10 for example)
char * itoa(int i, char * dest, int radix)
to convert your int to a string
and then use strcat(char * dest, const char * src)
you will end up with a string with dest+src
good luck.