cout 输出格式控制
如果要在输出流中加入格式控制符则要加载头文件:#include <iomanip>
这里面 iomanip 的作用比较多:
主要是对 cin,cout 之类的一些操纵运算子,比如 setfill,setw,setbase,setprecision 等等。它是 I
/O 流控制头文件,就像 C 里面的格式化输出一样.以下是一些常见的控制函数的:
dec 置基数为 10 相当于"%d"
hex 置基数为 16 相当于"%X"
oct 置基数为 8 相当于"%o"
sample://作用永久
cout<<12<<hex<<12<<oct<<12<<12;output 12c1414
setprecision(n) 设显示小数精度为 n 位 //作用永久
sample: setf(ios:fixed);
cout<<setprecision(2)<<2.345<<endl; ouput 2.34 //注意先用 setf(ios::fixed);否则结果自己测试下
setw(n) 设域宽为 n 个字符 //作用临时
这个控制符的意思是保证输出宽度为 n。如:
cout<<setw(3)<<1<<setw(3)<<10<<setw(3)<<100;输出结果为
1 10100 (默认是右对齐)当输出长度大于 3 时(<<1000),setw(3)不起作用。
setfill(c) 设填充字符为 c
setioflags(ios::fixed)固定的浮点显示
setioflags(ios::scientific) 指数表示
sample cout<<setiosflags(ios::fixed)<<setprecision(2)<<2.345<<endl; output 2.34
setiosflags(ios::left) 左对齐
setiosflags(ios::right) 右对齐
setiosflags(ios::skipws) 忽略前导空白
setiosflags(ios::uppercase) 16 进制数大写输出
setiosflags(ios::lowercase) 16 进制小写输出
setiosflags(ios::showpoint) 强制显示小数点
setiosflags(ios::showpos) 强制显示符号
sample: cout<<setiosflags(ios::uppercase)<<hex<<12<<15<<endl; output CF
cout<<setioflags(ios::showpoint)<<x<<endl;
若 float x=1,则 output 1.000000 不使用直接输出 1
cout<<setiosflags(ios::showpos)<<1<<endl;output +1
如果要在输出流中加入格式控制符则要加载头文件:#include <iomanip>
这里面 iomanip 的作用比较多:
主要是对 cin,cout 之类的一些操纵运算子,比如 setfill,setw,setbase,setprecision 等等。它是 I
/O 流控制头文件,就像 C 里面的格式化输出一样.以下是一些常见的控制函数的:
dec 置基数为 10 相当于"%d"
hex 置基数为 16 相当于"%X"
oct 置基数为 8 相当于"%o"
sample://作用永久
cout<<12<<hex<<12<<oct<<12<<12;output 12c1414
setprecision(n) 设显示小数精度为 n 位 //作用永久
sample: setf(ios:fixed);
cout<<setprecision(2)<<2.345<<endl; ouput 2.34 //注意先用 setf(ios::fixed);否则结果自己测试下
setw(n) 设域宽为 n 个字符 //作用临时
这个控制符的意思是保证输出宽度为 n。如:
cout<<setw(3)<<1<<setw(3)<<10<<setw(3)<<100;输出结果为
1 10100 (默认是右对齐)当输出长度大于 3 时(<<1000),setw(3)不起作用。
setfill(c) 设填充字符为 c
setioflags(ios::fixed)固定的浮点显示
setioflags(ios::scientific) 指数表示
sample cout<<setiosflags(ios::fixed)<<setprecision(2)<<2.345<<endl; output 2.34
setiosflags(ios::left) 左对齐
setiosflags(ios::right) 右对齐
setiosflags(ios::skipws) 忽略前导空白
setiosflags(ios::uppercase) 16 进制数大写输出
setiosflags(ios::lowercase) 16 进制小写输出
setiosflags(ios::showpoint) 强制显示小数点
setiosflags(ios::showpos) 强制显示符号
sample: cout<<setiosflags(ios::uppercase)<<hex<<12<<15<<endl; output CF
cout<<setioflags(ios::showpoint)<<x<<endl;
若 float x=1,则 output 1.000000 不使用直接输出 1
cout<<setiosflags(ios::showpos)<<1<<endl;output +1