C++用ios类的成员函数实现格式化I/O范例

代码:

#include <iostream>


#define ECHO(str) std::cout << str
#define ECHOLN(str) std::cout << str << std::endl


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char** argv) {

double d = 123.456789;

int i = 12345;

std::cout.setf(std::ios::showpos);//正数带 "+"
ECHOLN( d <<"    "<< i << "\t(showpos)");

std::cout.setf(std::ios::scientific);//科学计数法显示浮点数 
ECHOLN( d <<"    "<< i << "\t(showpos|scientific)" ); 

std::cout.setf(std::ios::showbase);//输出数据前带基数符
std::cout.setf(std::ios::hex);//十六进制显示整数 
ECHOLN( d <<"    "<< i << "\t(showpos|scientific|showbase|hex)" );//为什么这个不能用???? 


ECHO( std::hex << std::showbase);
ECHOLN( d <<"    "<< i << "\t(showpos|scientific|showbase|hex)" );

ECHOLN("====================================");
ECHOLN(""); 

ECHO("返回与流相关的当前标志:");
ECHOLN(std::cout.flags());//返回与流相关的当前标志

std::cout.unsetf(std::cout.flags());//返回当前的标志值并清除指定的标志 

ECHO("返回与流相关的当前标志:");
ECHOLN(std::cout.flags());//返回与流相关的当前标志

//设置域宽、小数点位数、和填充符

d = 123.456;
double f = 4567.89;

std::cout.setf(std::ios::showpoint);//设置浮点数带小数0
ECHOLN( d << "\t" << f << "\t(showpoint)");

std::cout.setf(std::ios::fixed);//使用定点形式
ECHOLN( d << "\t" << f << "\t(showpoint|fixed)");

std::cout.precision(5);//精度:5位数 
ECHOLN( d << "\t" << f << "\t(showpoint|fixed|precison)");

std::cout.width(20);//数据宽度:20
ECHOLN( d << "\t" << f << "\t(showpoint|fixed|precison|width)"); 

std::cout.width(20);//数据宽度:20
std::cout.fill('#');
ECHOLN( d << "\t" << f << "\t(showpoint|fixed|precison|width|fill)");  

std::cout.width(20);
std::cout.precision(1);
std::cout.fill('&');
ECHOLN(f);

return 0;
}


输出:

+123.457    +12345      (showpos)
+1.234568e+002    +12345        (showpos|scientific)
+1.234568e+002    +12345        (showpos|scientific|showbase|hex)
+1.234568e+002    0x3039        (showpos|scientific|showbase|hex)
====================================


返回与流相关的当前标志:0x1b08
返回与流相关的当前标志:0
123.456 4567.89 (showpoint)
123.456000      4567.890000     (showpoint|fixed)
123.45600       4567.89000      (showpoint|fixed|precison)
           123.45600    4567.89000      (showpoint|fixed|precison|width)
###########123.45600    4567.89000      (showpoint|fixed|precison|width|fill)
&&&&&&&&&&&&&&4567.9


--------------------------------
Process exited with return value 0
Press any key to continue . . .

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值