1

I am trying to get a double to be a string through stringstream, but it is not working.

std::string MatlabPlotter::getTimeVector( unsigned int xvector_size, double ts ){
    std::string tv;
    ostringstream ss;
    ss << "0:" << ts << ":" << xvector_size;
    std::cout << ss.str() << std::endl;
    return ss.str();
}

It outputs only "0:" on my console...

I'm working on two projects, both with the same problem. I'm posting a different one, which runs into the same problem. It is posted here:
http://pastebin.com/m2dd76a63
I have three classes PolyClass.h and .cpp, and the main. The function with the problem is PrintPoly. Can someone help me out? Thanks a bunch!!

4

5 回答 5

4

您打印正确,但是您的打印顺序逻辑不正确。我修改了它以按照我认为你想要的方式工作,如果这有帮助,请告诉我。 http://pastebin.com/d3e6e8263

老答案:

您的代码有效,但ostringstream位于std名称空间中。问题出在您的文件打印代码中。

我可以看到您对该函数的调用吗?

我做了一个测试用例:

// #include necessary headers
int main(void)
{
  std::string s;
  s = MatlabPlotter::getTimeVector(1,1.0);
}

我得到的输出是0:1:1

于 2009-10-19T21:07:22.507 回答
2

以下代码是 100% 正确的:

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

// removed MatlabPlotter namespace, should have no effect
std::string getTimeVector(unsigned int xvector_size, double ts)
{
    // std::string tv; // not needed
    std::ostringstream ss;
    ss << "0:" << ts << ":" << xvector_size;

    std::cout << ss.str() << std::endl;

    return ss.str();
}

int main(void)
{
    // all work
    // 1:
    getTimeVector(0, 3.1415);

    // 2: (note, prints twice, once in the function, once outside)
    std::cout << getTimeVector(0, 3.1415) << std::endl;

    // 3: (note, prints twice, once in the function, once outside)
    std::string r = getTimeVector(0, 3.1415);
    std::cout << r << std::endl;
}

找出我们的不同之处,这可能是您的错误来源。因为它停在你的双倍,我猜你试图打印的双倍是无穷大、NaN(不是数字)或其他一些错误状态。

于 2009-10-19T22:31:26.110 回答
1

我无法真正帮助解决其中的“无输出”部分,因为您没有显示尝试输出此内容的代码。作为猜测,您是否可能没有以某种方式将 EOL 放在那里?有些系统在遇到换行符之前不会给出任何文本输出。您可以通过将 a 附加<< std::endl到您的线路或 a'\n'到您的字符串来做到这一点。

由于您没有为它设置 using ,因此您需要使用 type std::ostringstream。这类似于您必须使用“std:string”而不仅仅是“string”。

另外,如果是我,我会摆脱那个临时变量,只是return ss.str();它的代码更少(可能会出错),并且程序的工作可能更少。

于 2009-10-19T21:09:07.017 回答
0

感谢大家的意见!不确定确切的错误,但一定是 XCode 中的某些设置搞砸了。我制作了一个 CMakeLists.txt 文件,并使用从终端编译它
cmake -G XCode .. 并生成了一个 XCode 项目。我运行了它,现在它工作正常......现在有人会碰巧知道什么可能导致 XCode 这样做吗?我正在使用以下版本运行 3.2 版:
64 位
组件版本
Xcode IDE:1610.0
Xcode Core:
1608.0 ToolSupport:1591.0

于 2009-10-21T03:40:23.020 回答
0

好吧,我尝试了您链接到的代码并输出

 B 4
 A 5
 B 4
 C 3
x^ + 5x^ + 3

尽管崩溃发生在 PrintPoly 之后,但在崩溃之前对我来说。通过查看代码,这就是我期望它打印的内容。你是说字母后面没有出现整数吗?

于 2009-10-20T20:59:08.520 回答