How do I concatenate multiple C++ strings on one line?(如何在一行上连接多个 C++ 字符串?)
问题描述
C# 有一个语法特性,您可以在一行中将多种数据类型连接在一起.
C# has a syntax feature where you can concatenate many data types together on 1 line.
string s = new String();
s += "Hello world, " + myInt + niceToSeeYouString;
s += someChar1 + interestingDecimal + someChar2;
C++ 中的等价物是什么?据我所知,您必须在单独的行上完成所有操作,因为它不支持使用 + 运算符的多个字符串/变量.这还可以,但看起来不那么整洁.
What would be the equivalent in C++? As far as I can see, you'd have to do it all on separate lines as it doesn't support multiple strings/variables with the + operator. This is OK, but doesn't look as neat.
string s;
s += "Hello world, " + "nice to see you, " + "or not.";
上面的代码产生了一个错误.
The above code produces an error.
推荐答案
#include <sstream>
#include <string>
std::stringstream ss;
ss << "Hello, world, " << myInt << niceToSeeYouString;
std::string s = ss.str();
看看 Herb Sutter 的这篇本周大师文章:庄园农场的字符串格式化程序
Take a look at this Guru Of The Week article from Herb Sutter: The String Formatters of Manor Farm
这篇关于如何在一行上连接多个 C++ 字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在一行上连接多个 C++ 字符串?
- 静态初始化顺序失败 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 近似搜索的工作原理 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- C++ 协变模板 2021-01-01
- 从python回调到c++的选项 2022-11-16
- 如何对自定义类的向量使用std::find()? 2022-11-07