常用的格式输出,经常忘记C++的输出, 几个主要点:设置输出位数,设置填充,设置对齐
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
// 位数输出
int n = 10;
cout <<"0: " <<setw(4) <<setfill('w') <<setiosflags(ios::left) <<n <<endl;
// 输出流中一次改变即不会自动变回来, setfill对下一个适用
cout <<"1: " <<setw(4) <<setiosflags(ios::right) <<n <<endl;
cout <<"2: " <<setw(4) <<setfill('0') <<setiosflags(ios::right) <<n <<endl;
return 0;
}
进制输出, 一个重要的函数 setiosflags(),同上设置对齐格式,默认右对齐。
标准函数 | 作用 |
ios::left | 设置输出左对齐 |
ios::right | 设置好输出右对齐 |
ios::dec | 设置十进制输出 |
ios::oct | 设置八进制输出 |
ios::hex | 设置十六进制输出 |
ios::fixed | 设置以定点数输出 |
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
int n = 10;
cout <<"4: 十进制输出 " <<dec <<n <<endl;
cout <<"5: 十六进制输出 " <<hex <<n <<endl;
cout <<"6: 八进制输出 " <<oct <<n <<endl;
cout <<dec <<endl;
float d = 7;
cout <<"7: " <<setw(4) <<d/3 <<endl; //setw 并不起作用
cout <<"8: " <<setprecision(4) <<d/3 <<endl; // 单独 setprecision, 设置总位数
cout <<"9: " <<setiosflags(ios::fixed) <<d/3 <<endl;
// 定点数输出,表示小数点后固定位数
cout <<"10: " <<setprecision(6) <<setiosflags(ios::fixed) <<d/3 <<endl;
return 0;
}
总结:小数输出,setprecision 和 ios::fixed ,组合使用,也可单独使用
字符输出,字符输出位数setw, 字符填充 setfill, 左右对齐格式(ios::left ,ios::rigth)
整数输出,字符输出基础上增加进制输出 。