ostream类包含一些可用于控制格式的成员函数
这里介绍一个简单的setf(),可用于避免科学计数法
std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield);
这设置了cout对象的一个标记,命令cout使用定点表示法
std::cout.precision(3);
表示cout在使用定点表示法时,显示三位小数
程序:未使用setf()函数
int main(void)
{
Stock fluffy_the_cat;
//std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield);
//std::cout.precision(3);
fluffy_the_cat.acquire("NanoSmart", 20, 12.50);
fluffy_the_cat.show();
fluffy_the_cat.buy(15, 18.125);
fluffy_the_cat.show();
fluffy_the_cat.sell(400, 20.00);
fluffy_the_cat.show();
fluffy_the_cat.buy(300000, 40.125);
fluffy_the_cat.show();
fluffy_the_cat.sell(300000, 0.125);
fluffy_the_cat.show();
std::cin.get();
return 0;
}
程序:使用setf()函数后
int main(void)
{
Stock fluffy_the_cat;
std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield);
std::cout.precision(3);
fluffy_the_cat.acquire("NanoSmart", 20, 12.50);
fluffy_the_cat.show();
fluffy_the_cat.buy(15, 18.125);
fluffy_the_cat.show();
fluffy_the_cat.sell(400, 20.00);
fluffy_the_cat.show();
fluffy_the_cat.buy(300000, 40.125);
fluffy_the_cat.show();
fluffy_the_cat.sell(300000, 0.125);
fluffy_the_cat.show();
std::cin.get();
return 0;
}
##################################################
上述格式修改将一直有效,知道再次被修改,所以它们可能影响客户程序中的后续输出。
我们可以重置格式信息,使其恢复到自己被调用前的状态
std::streamsize prec=std::cout.precision(3); //save preceding value for precision
std::cout.precision(prec); //reset to old value
//store original flags
std::ios_base::fmtflags orig = std::cout.setf(std::ios_base::fixed);
//reset to stored values
std::cout.setf(orig, std::ios_base::floatfield);