Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 276
  • Last Modified:

Append int to end of C string

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.
1 Solution
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.
010101010101Author Commented:

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.
010101010101Author Commented:
Ok. figured it out. I simply added 48 to the number (ascii table) I wanted, then set strlen = number, then strlen+1 = '\0'. Thanks.
Thats fine for 0-9, but you asked about 0-25. So try this...

for(x=0; x<25; x++)
  sprintf(str, "%s %d", x);

or if you dont want the 10s digit...

for(x=0; x<25; x++)
  sprintf(str, "%s%d", x % 10);

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.

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now