iomanip

阅读量: 160 编辑

iomanip 函数库是C++中的输入输出流操纵库,用于格式化输入和输出。它提供了一些函数和操纵符,可以用于更精确地控制C++程序的输入和输出。需要添加:

#include <iomanip>

一、函数库

setprecision:用于设置输出流的精度,即小数点后的位数。

setw:用于设置字段宽度,即输出占位。

setfill:用于设置填充字符,即在字段宽度填充对应字符。

leftright: 左对齐 和 右对齐。

fixed:用于指定浮点数的输出格式,fixed 用于固定小数点表示。

scientific:用于科学计数法表示。

showpos:显示正负号

二、程序案例

1、设置小数位数

setprecision:用于设置输出流的精度,即小数点后的位数。例如:

// 爱码岛编程
#include <iomanip>
#include <iostream>
using namespace std;

int main() {
  double number = 3.141592653589793;
  cout << setprecision(2) << number << endl;
  return 0;
}

也可以用 cout.precision 实现相同的小数点展示。

// 爱码岛编程
#include <iostream>
using namespace std;

int main() {
  cout.flags(ios::fixed);
  cout.precision(2);

  double number = 3.141592653589793;
  cout << number << endl;

  return 0;
}

2、设置字段宽度

setw:用于设置字段宽度,即输出占位。例如:

// 爱码岛编程
#include <iomanip>
#include <iostream>
using namespace std;

int main() {
  int num1 = 42;
  int num2 = 12345;

  // setw(10),设置10个宽度
  cout << setw(10) << num1 << setw(10) << num2 << endl;
  return 0;
}

3、字符填充

setfill:用于设置填充字符,即在字段宽度填充对应字符。例如:

// 爱码岛编程
#include <iomanip>
#include <iostream>
using namespace std;

int main() {
  int num = 42;

  // 8个*填充
  cout << setw(10) << setfill('*') << num << endl;
  return 0;
}

4、设置文本对齐方式

leftright: 左对齐 和 右对齐。例如:

// 爱码岛编程
#include <iomanip>
#include <iostream>
using namespace std;

int main() {
  // 左对齐Left占4个位置(宽度共10)
  cout << left << setw(10) << "Left";

  // 左对齐Right占5个位置(宽度共10)
  cout << setw(10) << "Right" << endl;
  
  // 显示正负号
  cout << showpos << 10 << endl;
  
  return 0;
}

5、浮点数输出格式

fixedscientific:用于指定浮点数的输出格式。fixed 用于固定小数点表示,scientific 用于科学计数法表示。例如:

// 爱码岛编程
#include <iomanip>
#include <iostream>
using namespace std;

int main() {
  double number = 0.00016345;
  cout << fixed << number << endl;
  cout << scientific << number << endl;

  // 结合setprecision使用
  cout << fixed << setprecision(4) << number << endl;
  return 0;
}
爱码岛编程公众号
试卷资料
爱码岛编程小程序
在线刷题
苏ICP备13052010号
©2023 南京匠成信息科技有限公司