You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++如何向stringstream中添加字符串以完成多字符串合并?

C++ 多字符串合并实现方案

你示例中的std::stringstream不存在add方法,正确的实现可以参考以下几种方案:

方案1:基于std::stringstream实现(匹配你原思路的修正版)

std::stringstream使用**流插入运算符<<**完成内容写入,修正后的代码如下:

#include <sstream>
#include <string>

int main() {
    std::stringstream ss;
    std::string str_one = "hello ";
    std::string str_two = "world!\n";
    // 逐次写入内容,也可以连写为 ss << str_one << str_two;
    ss << str_one;
    ss << str_two;

    std::string result = ss.str();
    return 0;
}

该方案的优势是支持同时拼接不同类型的变量(比如int、double、C风格字符串等),不需要手动做类型转换,适合复杂格式化拼接场景。

方案2:直接使用std::string的拼接运算符(简单场景首选)

如果仅需拼接字符串类型变量,不需要额外格式化,直接使用+/+=运算符更简洁高效:

#include <string>

int main() {
    std::string str_one = "hello ";
    std::string str_two = "world!\n";
    // 直接拼接得到结果,多段字符串也可以连写:a + b + c + d
    std::string result = str_one + str_two;
    // 增量拼接可使用 +=:str_one += str_two;
    return 0;
}
  • 拼接大量字符串时,可提前调用std::string::reserve()预分配足够内存,避免多次扩容带来的性能损耗。

方案3:C++20及以上版本使用std::format

如果需要同时做格式化和拼接,C++20标准新增的std::format是更安全高效的选择:

#include <string>
#include <format>

int main() {
    std::string str_one = "hello ";
    std::string str_two = "world!\n";
    std::string result = std::format("{}{}", str_one, str_two);
    return 0;
}

内容的提问来源于stack exchange,提问作者Kemsikov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 12:54:04