pax*_*blo 7 c++ string cout std
我有一些代码,以最小的完整形式展示问题(在提问时成为一个好公民),基本归结为以下几点:
#include <string>
#include <iostream>
int main (void) {
int x = 11;
std::string s = "Value was: " + x;
std::cout << "[" << s << "]" << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
而且我期待它输出
[Value was: 11]
Run Code Online (Sandbox Code Playgroud)
相反,而不是那样,我只是:
[]
Run Code Online (Sandbox Code Playgroud)
这是为什么?为什么我不能输出我的字符串?字符串是空白的吗?被cout
莫名其妙地坏了吗?我疯了吗?
"Value was: "
是类型的const char[12]
.向其中添加整数时,您实际上是引用该数组的元素.要查看效果,请更改x
为3
.
你必须std::string
明确地构建一个.然后,你不能连接一个std::string
和一个整数.要解决这个问题,您可以写入std::ostringstream
:
#include <sstream>
std::ostringstream oss;
oss << "Value was: " << x;
std::string result = oss.str();
Run Code Online (Sandbox Code Playgroud)