Avatar of 010101010101
010101010101
 asked on

Append int to end of C string

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

Avatar of undefined
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.
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
ASKER CERTIFIED SOLUTION
TheBeaver

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
tommydoyle

int i;
int slen;  /*The length of you string*/

slen = strlen(yourstring);

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.