
有时人们可能会希望强制一个值在其字段的左侧打印,而在右边填充空格。为此可以使用 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 objectsusing 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
| 流 *** 作符 | 描 述 |
|---|---|
| setw(n) | 为下一个值的输出设置最小打印字段宽度为 n |
| fixed | 以固定点(例如小数点)的形式显示浮点数 |
| showpoint | 显示浮点数的小数点和尾数 0,即使没有小数部分也一样 |
| setprecision(n) | 设置浮点数的精度 |
| left | 使后续输出左对齐 |
| right | 使后续输出右对齐 |
总结
以上是内存溢出为你收集整理的C++ left和right *** 作符用法详解全部内容,希望文章能够帮你解决C++ left和right *** 作符用法详解所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)