您的位置:首页 > 编程语言 > C语言/C++

C++格式化输出

2017-09-13 16:30 246 查看
#include <iostream>

#include <iomanip>

using namespace std;

int main()

{
//格式化输入输出 保留小数点后几位
double m = 5.62;
cout << m << " " << endl
<< "保留小数点后10位" << setiosflags(ios::fixed) << setprecision(10) << m
<< endl;

//控制bool的输出格式
cout << "Default bool value: "
<< true << " " << false << endl;
cout << "BoolAlpha bool value: "
<< boolalpha << true << " " << false << endl;
//当使用boolalpha控制cout输出后,后续输出将不再按照0 1输出,使用noboolalpha可以取消
cout << true << " " << false << endl
<< noboolalpha << true << " " << false
<< endl;

//指定整型值的进制 oct hex dec 只影响整型运算对象,浮点型不受影响
cout << "Default: " << 20 << " " << 1024 << endl
<< "octal: " << oct << 20 << " " << 1024 << endl
<< "hex:" << hex << 20 << " " << 1024 << endl
<< "decimal: " << dec << 20 << " " << 1024 << endl;

//在输出中指出进制 showbase noshowbase 
cout << showbase;
cout << "Default: " << 20 << " " << 1024 << endl
<< "octal: " << oct << 20 << " " << 1024 << endl
<< "hex:" << hex << 20 << " " << 1024 << endl
<< "decimal: " << dec << 20 << " " << 1024 << endl;
cout << uppercase << showbase << hex
<< "Printed in hexadecimal: " << 20 << " " << 1024
<< nouppercase << noshowbase << dec << endl;

//控制浮点数格式,默认浮点值按6位精度打印,浮点没有小数部分,不打印小数点,根据值选择打印10进制或者科学计数法
//指定打印精度,控制打印精度通过四舍五入而非截断3.14159 -> 3.1416 
cout << "Precision: " << cout.precision()
<< ", value: " << sqrt(5.2) << endl;
cout.precision(15);//设置输出15个数字
cout << "Precision: " << cout.precision()
<< ", value: " << sqrt(5.2) << endl;
cout << setprecision(3);
cout << "Precision: " << cout.precision()
<< ", value: " << sqrt(5.2) << endl;

//指定浮点数计数法,若非必须由标准库选择计数法是最好的方式
//c++11
cout << "Default format: " << 100 * sqrt(5.5) << '\n'
<< "scientific: " << scientific << 100 * sqrt(5.5) << endl
<< "fixed decimal: " << fixed << 100 * sqrt(5.5) << endl
<< "hexadecimal: " << hexfloat << 100 * sqrt(5.5) << endl
<< "use default: " << defaultfloat << 100 * sqrt(5.5) << endl;

//showpoint强制打印小数点
cout << 5.0 << " " << showpoint << 5.0 << noshowpoint << endl;

//输出补白
int i = -55;
double d = 3.1415926;
//补白第一列,使用输出中最小n个位置
cout << "i: " << setw(18) << i << "next col" << '\n'
<< "d: " << setw(18) << d << "next col" << '\n';
//补白第一列,左对齐所有列
cout << left
<< "i: " << setw(18) << i << "next col" << '\n'
<< "d: " << setw(18) << d << "next col" << '\n'
<< right;
//补白第一列,右对齐所有列
cout << right
<< "i: " << setw(18) << i << "next col" << '\n'
<< "d: " << setw(18) << d << "next col" << '\n'
<< left;
//补白第一列,补在域内部
cout << internal
<< "i: " << setw(18) << i << "next col" << '\n'
<< "d: " << setw(18) << d << "next col" << '\n';
//补白第一列,#作为补白字符
cout << setfill('@')
<< "i: " << setw(18) << i << "next col" << '\n'
<< "d: " << setw(18) << d << "next col" << '\n'
<< setfill(' ');
system("pause");
return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息