[C++]输入输出流

来源:互联网 发布:中国软件资讯网 编辑:程序博客网 时间:2024/05/02 01:34

一、标准 I\O 流

标准I\O流的头文件iostream。提供了I\O库,也提供了使用该库的流模式, "cin>>"从输入设备流入和“cout<<”流出到输出设备。

1、常用的流状态
showpos        在正数(包括0)之前加+号;
showbase       十六进制整数前加OX,八进制前加O;
uppercase     十六进制格式字母用大写字母表示(默认是小写);
showpoint       浮点输出,即使小数点之后全为0也加小数点;
boolalpha     逻辑值1和0用true和false表示;
left           左对齐(填充字符填在左边);
right         右对齐(填充字符填在右边);
dec         十进制显示整数
hex           十六进制显示整数
oct             八进制显示整数
fixed           常规小数格式输出
scientific     科学计数法格式输出
取消流状态的操作:noshowpos  noshowpoint nouppercase  noshowbase  noboolalpha
dec oct hex
三者, left与right 这两者相互独立,设置了此,就抵消了彼.   fixed与scientific和一般显示方式三者独立,不过他们的取消方式比较别扭,为cout捆绑函数调用方式:cout.unsetf(ios::scientific) 

示例代码:(VS2013代码测试通过)
       cout << showpos << 12 << noshowpos << endl;//输出:+12
cout << hex << 18 << " " << showbase << 18 << noshowbase << endl;//输出:12 OX12
cout << hex << 255 << " " << uppercase << 255 << nouppercase << endl;//输出:ff FF
cout << dec; //取消十六进制显示
cout << 123.0 << " " << showpoint << 123.0 << noshowpoint << endl;//输出:123 123.000
cout << (2 > 3) << " " << boolalpha << (2>3) << noboolalpha << endl;//输出:0 false
cout << fixed << 12345.678 << endl;//输出:12345.678000
cout << scientific << 12345.678 << endl;  //输出:1.234568e+004

2、有参数的三个常用的流状态
cout.width(int)设置显示宽度,并且width()为一次性操作,即第二次显示将不再有效;
cout.fill(char)    fill('')
(注意是单引号)设置填充字符;
cout.precision(int)设置有点位数(普通显示方式)或者精度(定点或者科学计数法方式)
示例代码(VS2013测试通过)
cout.width(5);
cout.fill('s');
cout << 23 << 23<<endl;
3、与流输出符<<连用的设置方式(需包含头文件iomanip)
setw(int);
setfill(char);
setprecision(int);
示例代码(VS2013测试通过):
cout << setw(5) << setfill('$') << 27<<endl;

4、string类型更简洁的设置方法(可以定义重复N次字符的字串,还可以字串相加)
示例代码:(倒三角形)
cout << string(n, ' ') +string(21-2*n,'M') + "\n";




0 0
原创粉丝点击