c语⾔right,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
#include // Header file needed to use stream manipulators
#include // 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 <
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;
c语言return的用法和搭配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
使后续输出右对齐