【问题标题】:Why is my string not being printed?为什么我的字符串没有被打印?
【发布时间】:2011-02-03 06:09:55
【问题描述】:

我有一些代码,以最小的完整形式展示了问题(在提出问题时做一个好公民),基本上可以归结为以下内容:

#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 是否以某种方式损坏了?我是不是疯了?

【问题讨论】:

  • 顺便说一句,您需要包含 &lt;string&gt; 才能以合规的方式“工作”。
  • 好点,这怎么编译?
  • gcc (Ubuntu 4.4.3-4ubuntu5) 4.4.3 编译时没有错误 - 也许只是宽容。在任何情况下,添加字符串都无济于事,所以我将它添加到问题中,这样我们就更洁净了。但是,Xeo 打败了我,所以谢谢 :-)

标签: c++ string std cout


【解决方案1】:

"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();

【讨论】:

  • 在这种情况下,由于数字是11,字符串的长度是11,所以结果指针指向空终止符。
  • 实际上是const char[12] 类型。
  • char[11] 实际上(我认为)。
  • @hype:不,它不能。这给出了 no match for ‘operator+’ in std::basic_string 错误。
  • @pax: §2.13.4/1, C++03: “一个普通的字符串字面量具有“n const char 数组”类型和静态存储持续时间 (3.7),其中 n 是大小字符串”
【解决方案2】:

你不能像那样添加字符指针和整数(你可以,但它不会像你期望的那样)。

您需要先将 x 转换为字符串。您可以通过使用 itoa 函数将整数转换为字符串以 C 方式进行带外操作:

char buf[5];
itoa(x, buf, 10);

s += buf;

或带有 sstream 的 STD 方式:

#include <sstream>

std::ostringstream oss;
oss << s << x;
std::cout << oss.str();

或者直接在 cout 行:

std::cout << text << x;

【讨论】:

  • 不会因为 x 是 int 类型而不是 string 或 char* 而遇到问题吗?
  • 这给了我[Value was &lt;CTRL-K&gt;](必须通过od -xcb 来查看那里发生了什么。
  • 当您执行S += x; 时,它会将整数 11 转换为 char 11 并尝试获取相应的 ASCII 字符。
【解决方案3】:

有趣 :) 这就是我们为 C 兼容性和缺少内置 string 而付出的代价。

无论如何,我认为最易读的方法是:

std::string s = "Value was: " + boost::lexical_cast<std::string>(x);

因为这里lexical_cast的返回类型是std::string,所以会选择+的右重载。

【讨论】:

    【解决方案4】:

    C++ 不使用 + 运算符连接字符串。也没有从数据类型到字符串的自动提升。

    【讨论】:

      【解决方案5】:

      在 C/C++ 中,不能使用 + 运算符将整数附加到字符数组,因为 char 数组会衰减为指针。要将int 附加到string,请使用ostringstream

      #include <iostream>
      #include <sstream>
      
      int main (void) {  
        int x = 11;
        std::ostringstream out;
        out << "Value was: " << x;
        std::string s = out.str();
        std::cout << "[" << s << "]" << std::endl;
        return 0;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-02-21
        • 2021-03-06
        • 2021-11-23
        • 2020-03-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多