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

C++流操作算子

2016-04-21 21:39 489 查看
用过c语言的都知道c语言的精度格式控制非常简单容易,刚学C++也许还不懂怎么在C++中使用这些功能.这里有两个方法来使用这些功能.

变量使用:

int n = 64;
double d = 123.45;
double d2 = 0.0183;


一.使用流操纵算子

首先得包含头文件

1.宽度控制

cout << n << '#' << endl;
//宽度控制不会影响下一个变量
cout << setw(10) << n << '#' << endl;//默认右对齐
cout << n << '#' << endl;




2.对齐控制

//对齐控制会影响下面的变量对其方式
cout << setw(10) << setiosflags(ios::left) << n << '#' << endl;//左对齐
cout << setw(10) << n << '#' << endl;
cout << setw(10) << setiosflags(ios::right) << n << '#' << endl;//还原成右对齐
//cout << setw(10) << resetiosflags(ios::left) << n << '#' << endl << endl;//还原成右对齐




3.填充控制

//填充控制会影响下面的输出
cout << setw(10) << setfill('@') << n << '#' << endl;
cout << setw(10) << n << '#' << endl;
cout << setw(10) << setfill(' ') << n << '#' << endl; //还原成空格填充




4.精度控制

//精度控制会影响下面的输出
cout << setprecision(4) << d << endl; //控制有效数字的位数
cout << setprecision(2) << d2 << endl;//四舍五入,而不是简单的截断
cout << d << endl;
cout << setiosflags(ios::fixed);      //控制小数点后面的位数
cout << setprecision(4) << d << endl; //同样是四舍五入
cout << setprecision(2) << d2 << endl;




5.进制控制

cout << "dec: " << n << endl;
cout <<"oct: "<<oct << n << endl;
cout << "hex: " << hex << n << endl;
cout << n << endl;
cout << setiosflags(ios::showbase);//显示对应进制前面的符号
cout << "dec: " << dec <<n << endl;
cout << "oct: " << oct << n << endl;
cout << "hex: " << hex << n << endl;
cout << setbase(8) << n << endl;   //进制输出
cout << setbase(10) << n << endl;
cout << setbase(16) << n << endl;




二.以流成员函数的方式(不用包含iomanip头文件)

1.宽度控制

cout << n << endl;
cout.width(10);
cout << n << '#' << endl;




2.对齐控制

cout << n << endl;
cout.width(10);
cout.setf(ios::left);
cout << n << '#' << endl;
//  cout.width(10);
//  cout.setf(ios::right);
//  cout << n << '#' << endl;
cout.width(10);
cout.unsetf(ios::left);
cout << n << '#' << endl;




3.填充控制

cout << n <<'#'<< endl;
cout.width(10);
cout.fill('@');
cout << n << '#' << endl;
cout.width(10);
cout << n << '#' << endl;
cout.width(10);
cout.fill(' ');
cout << n << '#' << endl;




4.精度控制

cout.precision(2);   //这个会影响下面的输出
cout << d << endl;
cout << d2 << endl;
cout.setf(ios::fixed);  //控制小数点位数
cout << d << endl;
cout << d2 << endl;




5.进制控制

cout.unsetf(ios::dec); //要切换进制的时候需要先去掉原先的进制
cout.setf(ios::oct);
cout << n << endl;


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