
720
720.0
720.00000000
7.2E+ 2
720.0
// 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
34 7 1623
390 3456 12
为了弥补这一点,cout 提供了一种指定每个号码使用的最小空格数量的方法。流 *** 作符 setw 可用于建立指定宽度的打印区域。以下是其用法示例:
value = 23;
cout << setw(5) << value;
为了进一步解释其工作原理,请看以下语句:
value = 23;
cout << "(" << setw(5) << value << ")";
( 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 83734 7 1623390 3456 12注意,在程序第 3 行的 #include 指令中命名了一个新的头文件 iomanip。该文件必须包含在使用 setw 的任何程序中。
请注意,setw *** 作符要与每个值一起使用,这是因为 setw 只为紧随其后的值建立一个字段宽度。打印该值后,cout 将回到其默认的打印方式。如果数字太大导致字段无法完全容纳,那会怎么祥呢?如下列语句所示:
value = 18397;
cout << setw(2) << value;
可以为任何类型的数据指定字段宽度。下面的程序显示了与整数、浮点数及字符串对象一起使用的 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 objectsusing 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)此程序说明了一些要点:浮点数的字段宽度包括小数点的位置。字符串的字段宽度包括字符串中的所有字符,包括空格。默认情况下,该字段中打印的值为右对齐。这意味着它与打印字段的右侧对齐,并且必要时在值前填充空格。 总结
以上是内存溢出为你收集整理的C++ setw:格式化输出(详解版)全部内容,希望文章能够帮你解决C++ setw:格式化输出(详解版)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)