默認(rèn)情況下,用科學(xué)計(jì)數(shù)法表示實(shí)數(shù),輸出的指數(shù)位數(shù)為3。如何控制使其只輸出2位指數(shù)位?VC6下如何?VC2005又如何?
在VC2005下,運(yùn)行庫提供一個(gè)函數(shù)_set_output_format可以控制printf輸出的實(shí)數(shù)的指數(shù)位,要輸
出2位指數(shù)位需要這樣設(shè)置:
unsigned int old_exponent_format = _set_output_format(_TWO_DIGIT_EXPONENT);
使用完恢復(fù)原來設(shè)置:
_set_output_format(old_exponent_format);
在VC6中沒有此函數(shù),相同功能的函數(shù)我也沒有發(fā)現(xiàn)。
在C++標(biāo)準(zhǔn)庫中的stream中,我也沒有找到這樣的格式控制符。為了在VC6下完成此功能,最后只能
選擇曲線救國的道路了——?jiǎng)h除一個(gè)0。
1、對于printf這樣的輸出解決方法:
void EraseZeroPlus(std::string& str, string::size_type pos)


{
string::size_type pos1= str.find("E+", pos);

if(pos1 == string::npos)
return;
pos1 +=2;
str.erase(pos1, 1);

EraseZeroPlus(str, pos1);
}
void EraseZeroMinus(std::string& str, string::size_type pos)


{
string::size_type pos1= str.find("E-", pos);

if(pos1 == string::npos)
return;
pos1 +=2;
str.erase(pos1, 1);

EraseZeroMinus(str, pos1);
}

void EraseZero(char* szBuf, FILE* pFile)


{
string str(szBuf);
EraseZeroPlus(str, 0);
EraseZeroMinus(str, 0);
fputs(str.c_str(), pFile);
}
2、對于stream這樣的輸出解決方法:
這里只是考慮輸出文件的情況。
.h file
template<class _E, class _Tr = std::char_traits<_E> >
class my_ofstream : public std::basic_ofstream<_E, _Tr>


{
public:

my_ofstream()
{m_nPrecision = 5}
explicit my_ofstream(const char *_S,
ios_base::openmode _M = out | trunc)
: std::basic_ofstream<_E, _Tr>(_S, _M)

{
m_nPrecision = 5;
}
void set_precision(int nPre)

{
m_nPrecision = nPre;
}
int get_precision(void)

{
return m_nPrecision;
}

virtual ~my_ofstream()
{}
private:
int m_nPrecision;
};

typedef my_ofstream<char> myofstream;

// overload operator for double and float value
myofstream& operator<< (myofstream& strm, float value);
myofstream& operator<< (myofstream& strm, double value);.cpp file:
void erase_one_zero(std::string& str)


{
using namespace std;
string::size_type pos= str.length() - 3;
str.erase(pos, 1);
}
myofstream& operator<< (myofstream& strm, const float value)


{
using namespace std;
ostringstream oss;
oss << scientific << showpoint << setprecision(strm.get_precision()) << value;
std::string str(oss.str());
erase_one_zero(str);
strm << str;
return strm;
}

myofstream& operator<< (myofstream& strm, const double value)


{
using namespace std;
ostringstream oss;
oss << scientific << showpoint << setprecision(strm.get_precision()) << value;
std::string str(oss.str());
erase_one_zero(str);
strm << str;
return strm;
}test code:
int main(int argc, char* argv[])


{
using namespace std;

myofstream fout("out.txt");
fout << "out put scientific format: \n";
fout << 3654.002 << endl;
fout << 0.145f << endl;

fout.set_precision(6);
fout << 3654.002 << endl;
fout << 0.145f << endl;

return 0;
}VC6下,不知還有沒有更好的辦法……