如何在C中连接字符串和整数? [英] How to concatenate string and int in C?
本文介绍了如何在C中连接字符串和整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在循环的每次迭代中形成一个字符串,其中包含循环索引 i
:
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;
}
我尝试使用 strcat
和 itoa
的各种组合,但没有成功.
I tried using various combinations of strcat
and itoa
with no luck.
推荐答案
字符串在 C 中很困难.
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
}
}
12
是足够的字节来存储文本"pre_"
,文本"_suff"
,最多两个字符的字符串("99"
) 和 C 字符串缓冲区末尾的 NULL 终止符.
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.
这篇会告诉你如何使用snprintf
,但我推荐一本好的 C 书!
This will tell you how to use snprintf
, but I suggest a good C book!
这篇关于如何在C中连接字符串和整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文