如何形成 C++来自字符串文字串联的字符串?
我想连接字符串文字和整数,如下所示:string message("该值应介于 " + MIN_VALUE + " 和 " + MAX_VALUE);
但这给了我这个错误:
错误:类型 'const char*' 和 ' 的操作数无效const char [6]' 到二进制 'operator+'|
正确的方法是什么?我可以将其拆分为 2 个字符串声明(每个字符串声明连接一个字符串文字和一个 int),但这很丑陋。我也尝试过<<操作员。
谢谢
I would like concatenate string literals and ints, like this:string message("That value should be between " + MIN_VALUE + " and " + MAX_VALUE);
But that gives me this error:
error: invalid operands of types ‘const char*’ and ‘const char [6]’ to binary ‘operator+’|
What is the correct way to do that? I could split that in 2 string declarations (each concatenating a string literal and a int), but that's ugly. I've also tried << operator.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可能应该为此使用 stringstream。
You should probably use stringstream for this.
C++ 方法是使用 stringstream 然后你可以使用 stringstream <操作员。它会给你更一致的代码感觉
The c++ way to do this is to use a stringstream then you can use the << operator. It will give you a more consistent code feel
有很多方法可以做到这一点,但我最喜欢的是:
第一个文字周围额外的
string()
使世界变得不同,因为有一个重载的string::operator+(const char*)
返回一个string
,而operator+
具有从左到右的关联性,因此整个事情变成了一个operator+ 链
调用。There are many ways to do this, but my favourite is:
That extra
string()
around the first literal makes all the difference in the world because there is an overloadedstring::operator+(const char*)
which returns astring
, andoperator+
has left-to-right associativity, so the whole thing is turned into a chain ofoperator+
calls.您可能想使用这样的字符串流:
You probably want to use a stringstream like this: