C#有一个语法特性,您可以在一行中将许多数据类型连接在一起。
string s = new String();
s += "Hello world, " + myInt + niceToSeeYouString;
s += someChar1 + interestingDecimal + someChar2;
C++中的等价物是什么?据我所知,您必须在单独的行中完成所有这些操作,因为它不支持带有+运算符的多个字符串/变量。这是可以的,但看起来并不整洁。
string s;
s += "Hello world, " + "nice to see you, " + "or not.";
上面的代码产生了一个错误。
发布于 2009-03-19 16:27:20
#include <sstream>
#include <string>
std::stringstream ss;
ss << "Hello, world, " << myInt << niceToSeeYouString;
std::string s = ss.str();
看看这篇来自Herb Sutter的本周大师文章:The String Formatters of Manor Farm
发布于 2014-11-14 16:45:19
5年来没有人再提过.append
#include <string>
std::string s;
s.append("Hello world, ");
s.append("nice to see you, ");
s.append("or not.");
发布于 2009-03-19 16:26:24
s += "Hello world, " + "nice to see you, " + "or not.";
这些字符数组文字不是C++ std::strings您需要将它们转换为:
s += string("Hello world, ") + string("nice to see you, ") + string("or not.");
要转换int(或任何其他流类型),您可以使用boost lexical_cast或提供自己的函数:
template <typename T>
string Str( const T & t ) {
ostringstream os;
os << t;
return os.str();
}
你现在可以说这样的话:
string s = string("The meaning is ") + Str( 42 );
https://stackoverflow.com/questions/662918
复制相似问题