2013-10-17 56 views
2

我有一些前员工开发的C++代码。 我试图澄清/测试一些软件结果。 在中间步骤中,软件将结果保存到“二进制”dat文件中,然后由软件的另一部分导入。ofstream输出字符串/字符而不是双打

我的目标是将此输出从“二进制”更改为人类可读的数字。

输出文件被限定:

ofstream pricingOutputFile; 
double *outputMatrix[MarketCurves::maxAreaNr]; 
ofstream outputFile[MarketCurves::maxAreaNr]; 

的写入步骤是这样的一种:

pricingOutputFile.write((char *)&outputMatrix[area], sizeof(double)); 

基质填充有“双打”

有一种方法来改变这种输出一个人类可读的文件?

我已经尝试过各种std::stringcout和其他方法'谷歌搜索',但直到现在没有成功。

试过建议与< <,但给了以下错误: 错误C2297:“< <”:非法,右操作数的类型“双”

的sugestions她把我推在正确的轨道上:

sprintf_s(buffer, 10, "%-8.2f", rowPos); 
pricingOutputFile.write((char *)&buffer, 10); 

灵感发现在: http://www.tenouk.com/cpluscodesnippet/usingsprintf_s.html

感谢您的帮助

+1

你是怎么打印“输出”的?显示'outputMatrix'的声明 – P0W

+0

您是否尝试过类似'pricingOutputFile << outputMatrix [area] <<“\ n”;'? – timrau

回答

0

你可以只内联这样的:

pricingOutputFile << std::fixed 
        << std::setw(11) 
        << std::setprecision(6) 
        << std::setfill('0') 
        << rowMin; 

但是,这是非常必要的。我总是喜欢尽可能保持陈述。一个简单的方法来做到这一点是:

void StreamPriceToFile(ofstream & output, const double & price) const 
{ 
     output << std::fixed 
      << std::setw(11) 
      << std::setprecision(6) 
      << std::setfill('0') 
      << price; 
} 

//wherever used 
StreamPriceToFile(pricingOutputFile, rowMin); 

但即使是更好的(在我看来)会是这样的:

//setup stream to receive a price 
inline ios_base& PriceFormat(ios_base& io) 
{ 
     io.fixed(...); 
     ... 
} 

//wherever used 
pricingOutputFile << PriceFormat << rowMin; 

我的C++很生疏或者我会在PriceFormat填写。

+0

谢谢。 删除std :: setfill('0')&std :: fixed,因为这两个'设置'创建负数的问题,即:00-1.00000 但是,否则它做得很好! – Thorvall

1

在通过双占用的这段代码内存转储到一个文件

pricingOutputFile.write((char *)&outputMatrix[area], sizeof(double)); 

产生人类可读的,你需要使用重载的操作符< <:

pricingOutputFile << outputMatrix[area]; 
0

的sugestions她把我推正确的曲目:

sprintf_s(buffer,10,“%-8.2f”,rowPos); pricingOutputFile.write((char *)& buffer,10);

灵感发现在:http://www.tenouk.com/cpluscodesnippet/usingsprintf_s.html

+0

我不同意。你已经有一个流,只是使用它。如果你需要格式化双精度,[做它的字符串方式](http://stackoverflow.com/questions/11989374/floating-point-format-for-stdostream)。我相信这种方式更具可读性。 – PatrickV

+0

嗨帕特里克。 试图执行您的建议,但在尝试以下 – Thorvall

+0

错误时遇到了严重错误C3867:'std :: basic_ostream <_Elem,_Traits> :: write':函数调用缺少参数列表;使用 '&的std :: basic_ostream <_Elem,_Traits> ::写' 来创建一个指针构件 与 [ _Elem =炭, _Traits =标准:: char_traits ] 错误C2296: '<<':非法,左操作数的类型为'std :: basic_ostream <_Elem,_Traits>&(__ thiscall std :: basic_ostream <_Elem,_Traits> :: *)(const _Elem *,std :: streamsize)' 与 [ 1_Elem = char , _Traits = std :: char_traits ] error C2297:'<<':非法,右操作数的类型为'std :: ios_base&(__cdecl *)(std :: ios_base&)' – Thorvall