How to concatenate string and int in C?

CString

C Problem Overview


I need to form a string, inside each iteration of the loop, which contains the loop index i:

for(i=0;i<100;i++) {
  // Shown in java-like code which I need working in c!

  String prefix = "pre_";
  String suffix = "_suff";

  // This is the string I need formed:
  //  e.g. "pre_3_suff"
  String result = prefix + i + suffix;
}

I tried using various combinations of strcat and itoa with no luck.

C Solutions


Solution 1 - C

Strings are hard work in C.

#include <stdio.h>

int main()
{
   int i;
   char buf[12];
   
   for (i = 0; i < 100; i++) {
      snprintf(buf, 12, "pre_%d_suff", i); // puts string into buffer
      printf("%s\n", buf); // outputs so you can see it
   }
}

The 12 is enough bytes to store the text "pre_", the text "_suff", a string of up to two characters ("99") and the NULL terminator that goes on the end of C string buffers.

This will tell you how to use snprintf, but I suggest a good C book!

Solution 2 - C

Use sprintf (or snprintf if like me you can't count) with format string "pre_%d_suff".

For what it's worth, with itoa/strcat you could do:

char dst[12] = "pre_";
itoa(i, dst+4, 10);
strcat(dst, "_suff");

Solution 3 - C

Look at snprintf or, if GNU extensions are OK, asprintf (which will allocate memory for you).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjohnView Question on Stackoverflow
Solution 1 - CLightness Races in OrbitView Answer on Stackoverflow
Solution 2 - CSteve JessopView Answer on Stackoverflow
Solution 3 - CvanzaView Answer on Stackoverflow