为什么我的字符串没有被打印?
我有一些代码,以最小的完整形式展示了问题(在提出问题时成为一个好公民),基本上可以归结为以下内容:
#include <string>
#include <iostream>
int main (void) {
int x = 11;
std::string s = "Value was: " + x;
std::cout << "[" << s << "]" << std::endl;
return 0;
}
并且我期望它输出
[Value was: 11]
相反,而不是那样,我我只是:
[]
这是为什么?为什么我无法输出字符串?字符串是否为空? cout
是否有问题?我疯了吗?
I have some code that, in its smallest complete form that exhibits the problem (being a good citizen when it comes to asking questions), basically boils down to the following:
#include <string>
#include <iostream>
int main (void) {
int x = 11;
std::string s = "Value was: " + x;
std::cout << "[" << s << "]" << std::endl;
return 0;
}
and I'm expecting it to output
[Value was: 11]
Instead, instead of that, I'm getting just:
[]
Why is that? Why can I not output my string? Is the string blank? Is cout
somehow broken? Have I gone mad?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
“值是:”
的类型为const char[12]
。当您向其中添加一个整数时,您实际上是在引用该数组的一个元素。要查看效果,请将x
更改为3
。您必须显式构造一个
std::string
。话又说回来,您不能连接 std::string 和整数。要解决这个问题,您可以写入std::ostringstream
:"Value was: "
is of typeconst char[12]
. When you add an integer to it, you are effectively referencing an element of that array. To see the effect, changex
to3
.You will have to construct an
std::string
explicitly. Then again, you cannot concatenate anstd::string
and an integer. To get around this you can write into anstd::ostringstream
:您不能像这样添加字符指针和整数(可以,但它不会执行您期望的操作)。
您需要首先将 x 转换为字符串。您可以通过使用 itoa 函数将整数转换为字符串来以 C 方式在带外执行此操作:
或使用 sstream 的 STD 方式:
或者直接在 cout 行中执行此操作:
You can't add a character pointer and an integer like that (you can, but it won't do what you expect).
You'll need to convert the x to a string first. You can either do it out-of-band the C way by using the itoa function to convert the integer to a string:
Or the STD way with an sstream:
Or directly in the cout line:
有趣的是:)这就是我们为 C 兼容性和缺乏内置
字符串
付出的代价。无论如何,我认为最可读的方法是:
因为这里的
lexical_cast
返回类型是std::string
,所以+
的正确重载代码> 将被选择。Amusing :) That's what we pay for C-compatibility and the lack of a built-in
string
.Anyway, I think the most readable way to do it would be:
Because the
lexical_cast
return type isstd::string
here, the right overload of+
will be selected.C++ 不使用 + 运算符连接字符串。也没有从数据类型到字符串的自动提升。
C++ doesn't concatenate strings using the the + operator. There's also no auto-promote from data types to string.
在 C/C++ 中,无法使用
+
运算符将整数附加到字符数组,因为char
数组会衰减为指针。要将int
附加到string
,请使用ostringstream
:In C/C++, you cannot append an integer to a character array using the
+
operator because achar
array decays to a pointer. To append anint
to astring
, useostringstream
: