为什么我的字符串没有打印?

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莫名其妙地坏了吗?我疯了吗?

Osw*_*ald 8

"Value was: "是类型的const char[12].向其中添加整数时,您实际上是引用该数组的元素.要查看效果,请更改x3.

你必须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)

  • 它实际上是`const char [12]`类型. (2认同)
  • @pax:§2.13.4/ 1,C++ 03:"普通字符串文字的类型为"n const char"数组和静态存储持续时间(3.7),其中n是字符串的大小" (2认同)