C++牛人,字符串格式化问题.(Programmable formatting string)
char buf[80] = {0};
sprintf(buf, "%.16f ", nDoubleValue);
我想其中的16是可编程的,根据自己的意思来设定精度.
那么这个代码怎么写好呢?
偶的代码如下:
bool CMatrix::SaveDataIntoFile(string& strFileName, const unsigned long& nPrecision/* = 16*/)
{
ofstream outfile(strFileName.c_str(), ios_base::out);
if(!outfile)
{
cerr<<"cannot open "<<strFileName<< " for output."<<endl;
return false;
}
char buf1[80] = {0};
char buf2[80] = {0};
char CrLf[] = "\n";
char buf_format[80] = {0};
sprintf(buf_format, "%%.%dlf ", nPrecision);
for(unsigned long i = 0; i < m_nRow; ++i)
{
for(unsigned long j = 0; j < m_nCol; ++j)
{
sprintf(buf1, buf_format, m_pMatrix[i][j]);
outfile.write(buf1, sizeof(buf1));
strcpy(buf1, buf2);
}
outfile.write(CrLf, sizeof(CrLf) - 1);
}
outfile.close();
return true;
}
但我还是觉得有改进的余地,请指点.
我觉得爽的,给高分!
觉得这个帖子有学习意义的up一下,觉得这个帖子是垃圾的,down一下.
来个的,路过的兄弟姐妹,做个记号流个言在走.
:)