【问题标题】:The Str method of Stringstream will not work. (concatenation of different types) (C++)Stringstream 的 Str 方法将不起作用。 (不同类型的串联)(C++)
【发布时间】:2014-02-05 09:21:05
【问题描述】:

我是 C++ 新手,我正在尝试启动并运行一个简单的程序。

我在 Windows 系统上使用 Eclipse IDE(C++ 版本)。

我正在尝试连接一个输出语句,它将结合数字和字符串。

我知道在 Java 中,这是通过 System.out.println() 方法自动完成的。

我能够研究的是在 C++ 中实现这一点的一个好方法是使用字符串流方法。

#include <iostream>
#include <string>
#include "Person.h"

...

string simpleOutput(){
  stringstream ss;

  int a  = 50; // for testing purposes 
  int b = 60;
  string temp = "Random";
  ss << a << b << temp;
  return string output = ss.str();


}

当我尝试编译此代码时,得到以下信息:“方法“str”无法解析。

我还没有在任何网页上找到解决方案。 吨 谢谢!

【问题讨论】:

  • @Psypher 我完全不确定你指的是什么。 OP确实使用stringstream
  • @IvayloStrandjev 也许是stringsteam(缺少r)?
  • 我看到的是“stringsteam”,而不是“stringstream”(或者我读到 SO 太晚了)。
  • @Angew,WhozCraig 对 :) 抱歉。我仍然相信这只是一个错字。
  • @IvayloStrandjev 我也是。

标签: c++ string output stringstream


【解决方案1】:

您的主要问题是缺少包含:

#include <sstream>

另外,你在函数中有一个错字,你的 return 语句是彻头彻尾的疯狂。通过这些修复,它可以工作:

#include <iostream>
#include <string>
#include <sstream>

string simpleOutput(){
  stringstream ss;

  int a  = 50; // for testing purposes 
  int b = 60;
  string temp = "Random";
  ss << a << b << temp;
  return ss.str();
}

See it live

【讨论】:

  • 输入这个确切的代码块仍然会导致 Eclipse 注意到一个错误:“方法“str”无法解析”
  • 在 Eclipse 重启后代码可以工作,知道为什么会发生这种情况吗?
  • @user2879101 可能是包含文件的陈旧缓存。顺便说一句,“方法 str 无法解析。”听起来更像是来自 IDE 的消息,而不是来自编译器的消息。是实际的编译错误,还是 IDE 的自动完成问题?
  • 我相信这直接来自 Eclipse IDE,而不是编译器本身。
  • @user2879101 然后你也可以忽略它,或者通过清除缓存/重启来解决它(就像你做的那样)。 IDE 工具很容易混淆 - 如有疑问,请始终询问您的编译器。
【解决方案2】:

要使用stringstream,您需要#include &lt;sstream&gt;stringstream 也在 std 命名空间中定义,但从您的代码看来,您已经在使用此命名空间。代码的其他部分对我来说似乎是正确的。

【讨论】:

    【解决方案3】:

    你被 stringstream 的前向声明所困 - 只是 #include &lt;sstream&gt;

    也可以使用std::stringstreamstd::stringreturn ss.str()(刮掉string output

    进一步:将 using namespace::std 放在标头(全局范围)中是不好的。 见:Using std Namespace

    【讨论】:

    • 感谢您的提示!在我的原始代码中,我使用了 std 命名空间,有什么理由不应该使用它吗?
    • @user2879101 看看链接
    • 没关系,代码现在可以工作了……在 Eclipse 重新启动后。知道为什么需要重启 Eclipse 才能正确编译代码吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多