C++ ostream类包含的一个简单的用于控制格式的成员函数setf precision

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);

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值