【问题标题】:How to add string to stringstream?如何将字符串添加到字符串流?
【发布时间】:2021-09-05 08:31:07
【问题描述】:
我需要将很多字符串合并为一个。
像这样的
stringstream ss;
string str_one = "hello ";
string str_two = "world!\n";
ss.add(str_one);
ss.add(str_two);
string result = ss.str();
但是stringstream 中没有add 函数。我该怎么做?
【问题讨论】:
标签:
c++
string
stringstream
【解决方案1】:
stringstream 具有 operator<< 重载以将数据插入流中。它将返回对流本身的引用,因此您可以链接多个插入。
ss << str_one << str_two;
std::cout << ss.str(); // hello world!
作为替代方案,您可以利用fold expression(since C++17) 连接多个字符串。
template<typename ...T>
std::string concat(T... first){
return ((first+ ", ") + ...);
}
int main(){
std::string a = "abc", b = "def", c = "ghi", d = "jkl";
std::cout << concat(a, b, c, d); // abc, def, ghi,
}
折叠表达式展开如下:
"abc" + ("def" + ("ghi" + "jkl"));
Demo
【解决方案2】:
很简单,你要做的就是:
ss << " appended string";
【解决方案3】:
您可以像这样使用str() 方法:
std::string d{};
std::stringstream ss;
ss.str("hello this");
while(std::getline(ss, d)){
std::cout << d;
};