C语言 如何在C中连接字符串和整数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5172107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:57:07  来源:igfitidea点击:

How to concatenate string and int in C?

cstring

提问by john

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 strcatand itoawith no luck.

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

回答by Lightness Races in Orbit

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 12is 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结束。

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

这个会告诉你怎么用snprintf,不过我推荐一本好的C书!

回答by Steve Jessop

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

使用sprintf(或者snprintf如果像我一样你无法计算)格式 string "pre_%d_suff"

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");

回答by vanza

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

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