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

joh*_*ohn 66 c string

我需要在循环的每次迭代中形成一个字符串,其中包含循环索引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;
}
Run Code Online (Sandbox Code Playgroud)

我试图使用的各种组合strcat,并itoa没有运气.

Lig*_*ica 97

字符串在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
   }
}
Run Code Online (Sandbox Code Playgroud)

12是足够的字节来存储文本"pre_",文本"_suff",最多两个字符(串"99"),并且继续C字符串缓冲区的端NULL结束.

将告诉你如何使用snprintf,但我建议一本好的C书!

  • @R。我所展示的是,解决方案并不像 OP 所希望的那么容易。对某些人来说,“只是”抛弃这个概念比对其他人更难。 (4认同)
  • 不同之处在于,当某人忘记更改缓冲区大小时,您的代码会崩溃(或者更糟糕但会产生权限折衷),而使用`snprintf`的版本只会截断字符串.在任何情况下,我都会将缓冲区大小设置为"12 + 3*sizeof(int)",然后您不必担心......但使用`snprintf`仍然会更好. (3认同)
  • @R。当您更改 100 时,您会更改缓冲区大小。使用 `snprintf` 不会改变这一点;这只是意味着您还有一个地方可以写入和更新缓冲区大小。 (2认同)

Ste*_*sop 5

使用sprintf(或者snprintf如果像我一样,你不能计算)格式字符串"pre_%d_suff".

对于它的价值,使用itoa/strcat你可以做到:

char dst[12] = "pre_";
itoa(i, dst+4, 10);
strcat(dst, "_suff");
Run Code Online (Sandbox Code Playgroud)

  • “什么是‘itoa’”? (3认同)
  • 根据[c ++参考资料](http://www.cplusplus.com/reference/cstdlib/itoa/),关于`itoa`,声明"此函数未在ANSI-C中定义且不属于C++,但有些编译器支持." (2认同)