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

来源:互联网 发布:linux 获取返回值 编辑:程序博客网 时间:2024/06/10 00:24

代码:

#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);//设置浮点数带小数0ECHOLN( 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);//数据宽度:20ECHOLN( d << "\t" << f << "\t(showpoint|fixed|precison|width)"); std::cout.width(20);//数据宽度:20std::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 . . .

原创粉丝点击