我正在尝试通过stringstream将一个双精度值转换为字符串,但它不起作用。
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();
}它在我的控制台上只输出"0:“...
我正在做两个项目,都有同样的问题。我发布了一个不同的,它遇到了相同的问题。它在这里发布:
http://pastebin.com/m2dd76a63
我有三个类PolyClass.h和.cpp,以及main。有问题的函数是PrintPoly。有人能帮帮我吗?非常感谢!
发布于 2009-10-19 21:07:23
您的打印正确,但打印顺序中的逻辑不正确。我修改了它,以我认为你想要的方式工作,让我知道这是否有帮助。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-19 22:31:26
以下代码是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;
}找出我们的不同之处,这很可能是你的错误来源。因为它在您的double处停止,所以我猜测您尝试打印的double是infinity、NaN (不是数字)或其他错误状态。
发布于 2009-10-19 21:09:07
对于“无输出”这一部分,我真的帮不上忙,因为您没有显示尝试输出此输出的代码。作为猜测,你是不是不知何故没把EOL放进去?有些系统在遇到换行符之前不会给出任何文本输出。您可以通过将<< std::endl附加到行或将'\n'附加到字符串来完成此操作。
因为您没有指定它的用途,所以需要使用std::ostringstream类型。这类似于您必须使用"std:string“而不仅仅是"string”。
另外,如果是我的话,我会去掉temp变量,只是return ss.str();它的代码更少(可能会出错),程序的工作也可能更少。
https://stackoverflow.com/questions/1591140
复制相似问题