Alex Rivera | Logout

How to concatenate string and int in C?

Asked 2011-03-02T19:06:11.653
95

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.

Edit
Report

1 Answer

9

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");
answered 2011-03-02T19:08:36.947

Your Answer