C++ left和right操作符用法详解
发布时间:2020-12-16 07:38:55 所属栏目:百科 来源:网络整理
导读:正如学习 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 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 Highn"; 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
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |