C++ setw:格式化输出(详解版)
发布时间:2020-12-16 07:39:08 所属栏目:百科 来源:网络整理
导读:可以使用几种不同的方式打印或显示相同的数据。例如,以下数字虽然看起来不一样,但是它们都具有相同的值。 720 720.0 720.00000000 7.2E+ 2 720.0 打印值的方式称为 格式化 。cout 对象具有格式化每种数据类型变量的标准方式。当然,有时候需要对数据显示的
可以使用几种不同的方式打印或显示相同的数据。例如,以下数字虽然看起来不一样,但是它们都具有相同的值。
720 // This program displays three rows of numbers. #include <iostream> using namespace std; int main() { int num1 = 2897,num2 = 5,num3 = 837, num4 = 34,num5 = 7,num6 = 1623,num7 = 390,num8 = 3456,num9 = 12; // Display the first row of numbers cout << num1 << " " << num2 << " " << num3 << endl; // Display the second row of numbers cout << num4 << " " << num5 << " " << num6 << endl; // Display the third row of numbers cout << num7 << " " << num8 << " " << num9 << endl; return 0; }程序输出结果:
2897 5 837 为了弥补这一点,cout 提供了一种指定每个号码使用的最小空格数量的方法。流操作符 setw 可用于建立指定宽度的打印区域。以下是其用法示例:
value = 23; 为了进一步解释其工作原理,请看以下语句:
value = 23; (? ?23) 请注意,这个数字占据了字段的最后两个位置。由于这个数字没有使用整个字段,所以 cout 用空格填充了额外的 3 个位置。因为这个数字出现在字段的右侧,空格“填充”在前面,所以它被认为是右对齐的。下面的程序显示了如何通过使用 setw 来将之前程序中的数字打印在完美排列的列中。另外,由于程序使用 setw(6),最大的数字有 4 位,所以数字将被分开,而不必在数字之间打印一个包含空格的字符串文字。 // This program uses setw to display three rows of numbers so they align. #include <iostream> #include <iomanip>// Header file needed to use setw using namespace std; int main() { int num1 = 2897,num3 = 837,num4 = 34,num9 = 12; // Display the first row of numbers cout << setw(6) << num1 << setw(6) << num2 << setw(6) << num3 << endl; //Display the second row of numbers cout << setw(6) << num4 << setw(6) << num5 << setw(6) << num6 << endl; // Display the third row of numbers cout << setw(6) << num7 << setw(6) << num8 << setw(6) << num9 << endl; return 0; }程序输出结果: 2897 5 837 34 7 1623 390 3456 12注意,在程序第 3 行的 #include 指令中命名了一个新的头文件 iomanip。该文件必须包含在使用 setw 的任何程序中。 请注意,setw 操作符要与每个值一起使用,这是因为 setw 只为紧随其后的值建立一个字段宽度。打印该值后,cout 将回到其默认的打印方式。如果数字太大导致字段无法完全容纳,那会怎么祥呢?如下列语句所示:
value = 18397; 可以为任何类型的数据指定字段宽度。下面的程序显示了与整数、浮点数及字符串对象一起使用的 setw。 // This program demonstrates the setw manipulator //being used with variables of various data types. #include <iostream> #include <iomanip> // Header file needed to use setw #include <string> // Header file needed to use string objects using namespace std; int main() { int intValue = 3928; double doubleValue = 91.5; string stringValue = "Jill Q. Jones"; cout << "(" << setw (5) << intValue << ")" << endl; cout << "(" << setw (8) << doubleValue << ")" << endl; cout << "(" << setw (16) << stringValue << ")" << endl; return 0; }程序输出结果: ( 3928) ( 91.5) ( Jill Q. Jones)此程序说明了一些要点:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |