首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在一行中连接多个C++字符串?

如何在一行中连接多个C++字符串?
EN

Stack Overflow用户
提问于 2009-03-19 16:23:12
回答 19查看 461.3K关注 0票数 169

C#有一个语法特性,您可以在一行中将许多数据类型连接在一起。

代码语言:javascript
复制
string s = new String();
s += "Hello world, " + myInt + niceToSeeYouString;
s += someChar1 + interestingDecimal + someChar2;

C++中的等价物是什么?据我所知,您必须在单独的行中完成所有这些操作,因为它不支持带有+运算符的多个字符串/变量。这是可以的,但看起来并不整洁。

代码语言:javascript
复制
string s;
s += "Hello world, " + "nice to see you, " + "or not.";

上面的代码产生了一个错误。

EN

回答 19

Stack Overflow用户

回答已采纳

发布于 2009-03-19 16:27:20

代码语言:javascript
复制
#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

票数 272
EN

Stack Overflow用户

发布于 2014-11-14 16:45:19

5年来没有人再提过.append

代码语言:javascript
复制
#include <string>

std::string s;
s.append("Hello world, ");
s.append("nice to see you, ");
s.append("or not.");
票数 82
EN

Stack Overflow用户

发布于 2009-03-19 16:26:24

代码语言:javascript
复制
s += "Hello world, " + "nice to see you, " + "or not.";

这些字符数组文字不是C++ std::strings您需要将它们转换为:

代码语言:javascript
复制
s += string("Hello world, ") + string("nice to see you, ") + string("or not.");

要转换int(或任何其他流类型),您可以使用boost lexical_cast或提供自己的函数:

代码语言:javascript
复制
template <typename T>
string Str( const T & t ) {
   ostringstream os;
   os << t;
   return os.str();
}

你现在可以说这样的话:

代码语言:javascript
复制
string s = string("The meaning is ") + Str( 42 );
票数 76
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/662918

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档