在循环中连接Visual Studio C++ 6.0中的字符串

Ale*_*kov 0 c++ string concatenation

你能帮我用C++ for Visual Studio C++ 6.0优化这段代码:

char output[10000] = "";
for (int i = 0; i < cnt; i++) {
    char row[150];
    _snprintf(row, 149, "…", …);
    row[149] = '\0';
    strcat(output, row);
}
return _snprintf(buffer, size-1, "%s\r\nend\r\n", output);
Run Code Online (Sandbox Code Playgroud)

我需要的是我没有指定output []的大小但是动态地增加它.对于row []也是如此.对不起,我是C++的新手.

谢谢你的帮助.

Jon*_*rdy 6

在C++中,你应该使用std::string字符串代替char阵列,并std::stringstream和其表兄弟std::istringstreamstd::ostringstream代替sprintf()snprintf()在字符串缓冲区格式.这是C++解决方案的基础:

std::ostringstream result;
for (int i = 0; i < cnt; ++i) {
    result << "...\n";
}
result << "end\n";
return result.str();
Run Code Online (Sandbox Code Playgroud)

std::string级处理所有的内存管理的细节,并std::stringstream采用std::string内部.