cstring和int连接

这是变得比它应该更难(我没有交stream背景):

我需要在循环的每个迭代内部形成一个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: // eg "pre_3_suff" String result = prefix + i + suffix; } 

我尝试使用strcatitoa各种组合,没有运气。

string是艰苦的工作在C

 int main() { int i; char buf[12]; for (i = 0; i < 100; i++) { sprintf(buf, "pre_%d_suff", i); // puts string into buffer printf("%s\n", buf); // outputs so you can see it } } 

12是足够的字节来存储文本"_suff" ,文本"_suff" ,最多两个字符( "99" )的string和在Cstring缓冲区结束的NULL终止符。

这会告诉你如何使用sprintf ,但我build议一个好的C书!

使用格式string"pre_%d_suff" sprintf (或snprintf如果像我一样,你不能计数)。

用itoa / strcat你可以这样做:

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

看看snprintf,或者,如果GNU扩展是正确的, asprintf (它会为你分配内存)。

也许这个作品:

 int num = 1; char str1[] = "something"; char str2[] = num; str1 = str1 str2; 

去尝试一下!

 #include < string> #include < sstream> #include < iostream> #include < fstream> int main(){ ofstream fileHandle; stringstream fileName; myInt = 100; fileName << "filename_out_"; fileName << myInt << ".log"; fileHandle.open(fileName.str().c_str()); fileHandle << "Writing this to a file.\n"; fileHandle.close(); return 0; } 

//欢呼家伙