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++的新手.
谢谢你的帮助.
在C++中,你应该使用std::string字符串代替char阵列,并std::stringstream和其表兄弟std::istringstream和std::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内部.
| 归档时间: |
|
| 查看次数: |
1133 次 |
| 最近记录: |