C++ left和right操作符用法详解

  • 内容
  • 评论
  • 相关

正如学习 fixed、setprecision 和 showpoint 时的代码示例所看到的,cout 的输出是右对齐的,这意味着如果打印的字段大于显示的值,则值会被打印在字段的最右侧,带有前导空格。

有时人们可能会希望强制一个值在其字段的左侧打印,而在右边填充空格。为此可以使用 left 操作符。left 的左对齐设置将一直有效,直到使用 right 操作符将设置改回为右对齐。这些操作符可以用于任何类型的值,甚至包括字符串。

下面的程序说明了 left 和 right 操作符的用法。它还说明了 fixed、setprecision 和 showpoint 操作符对整数没有影响,只对浮点数有效。

// This program illustrates the use of the left and right manipulators.
#include <iostream>
#include <iomanip> // Header file needed to use stream manipulators
#include <string> // Header file needed to use string objects
using namespace std;

int main()
{
    string month1 = "January", month2 = "February", month3 = "March";
    int days1 = 31, days2 = 28, days3 = 31;
    double high1 = 22.6, high2 = 37.4, high3 = 53.9;
    cout << fixed << showpoint << setprecision(1);
    cout <<"Month       Days     High\n";
    cout << left << setw(12) << month1 << right << setw(4) << days1 << setw(9) << high1 << endl;
    cout << left << setw(12) << month1 << right << setw(4) << days1 << setw(9) << high1 << endl;
    cout << left << setw(12) << month1 << right << setw(4) << days1 << setw(9) << high1 << endl;
    return 0;
}

程序输出结果:

Month       Days     High
January       31     22.6
January       31     22.6
January       31     22.6

表 1 对 setw、fixed、showpoint、setprecision、left 和 right 共 6 种操作符进行了总结:

表 1 输出流操作符
流操作符 描 述
setw(n) 为下一个值的输出设置最小打印字段宽度为 n
fixed 以固定点(例如小数点)的形式显示浮点数
showpoint 显示浮点数的小数点和尾数 0,即使没有小数部分也一样
setprecision(n) 设置浮点数的精度
left 使后续输出左对齐
right 使后续输出右对齐

本文标题:C++ left和right操作符用法详解

本文地址:https://www.hosteonscn.com/3699.html

评论

0条评论

发表评论

邮箱地址不会被公开。 必填项已用*标注