How to concatenate string and int in C?

前端 未结 3 351
我在风中等你
我在风中等你 2020-12-07 17:27

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 cod         


        
相关标签:
3条回答
  • 2020-12-07 17:49

    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!

    0 讨论(0)
  • 2020-12-07 17:51

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

    0 讨论(0)
  • 2020-12-07 18:16

    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");
    
    0 讨论(0)
提交回复
热议问题