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

C++ left和right *** 作符用法详解,第1张

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

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

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

总结

以上是内存溢出为你收集整理的C++ left和right *** 作符用法详解全部内容,希望文章能够帮你解决C++ left和right *** 作符用法详解所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1231360.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-06
下一篇2022-06-06

发表评论

登录后才能评论

评论列表(0条)

    保存