简体   繁体   English

如何在C中连接字符串和int?

[英]How to concatenate string and int in C?

I need to form a string, inside each iteration of the loop, which contains the loop index i : 我需要在循环的每次迭代中形成一个字符串,其中包含循环索引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. 我尝试使用strcatitoa各种组合而没有运气。

Strings are hard work in C. 字符串在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. 12是足够的字节存储文本"pre_" ,文本"_suff" ,最多两个字符(串"99" ),并且继续C字符串缓冲区的端NULL结束。

This will tell you how to use snprintf , but I suggest a good C book! 将告诉你如何使用snprintf ,但我建议一本好的C书!

Use sprintf (or snprintf if like me you can't count) with format string "pre_%d_suff" . 使用格式字符串"pre_%d_suff" sprintf (或snprintf如果像我一样,你不能计算)。

For what it's worth, with itoa/strcat you could do: 对于它的价值,使用itoa / strcat你可以做到:

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

查看snprintf,或者,如果GNU扩展正常,则asprintf (将为您分配内存)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM