可以用几种不同的方法打印或显示相同的数据。 例如,以下数字看起来不同,但都具有相同的值。
720
720.0
720.00000000
7.2E 2
720.0
打印值的方法称为格式设置。 cout对象提供了一种设置每个数据类型变量格式的标准方法。 当然,您可能需要更多地控制数据的显示方式。 例如,以下程序显示三行数字,每行之间有一个空格。
//thisprogramdisplaysthreerowsofnumbers。
#包含
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;
返回0;
}
程序输出结果:
2897 5 837
34 7 1623
390 3456 12
美丽的是,数字没有按列对齐。 这是因为一些数字(如5和7 )在屏幕上占一个位置,而其他数字占2-3个位置。 cout只使用打印每个数字所需的空格数。
为了弥补这一点,cout提供了一种指定每个编号要使用的最小空格数的方法。 可以使用流操作符setw创建指定宽度的打印范围。 其使用示例如下所示。
value=23
coutsetw(5) value;
单词setw后括号中的数字表示后续值的字段宽度。 字段宽度是屏幕上打印值的最小字符位置或空格数。 在本例中,数字23显示在五个空间的字段中。
为了进一步说明其工作原理,请参阅以下语句。
value=23
cout'(setw )5) value ' );
这将产生以下输出:
(23 ) )。
请注意,这个数字占据了字段的最后两个位置。 因为这个数字没有使用整个字段,所以cout用空格填充了多余的三个位置。 此数字显示在字段的右侧,前面“填充”了空格,因此被视为右对齐。
以下过程说明如何使用setw将以前程序中的数字打印到完美的列中。 此外,程序使用setw(6),最大的数字为4位,因此不需要打印在数字之间包含空格的字符串文字,而是分割数字。
//thisprogramusessetwtodisplaythreerowsofnumberssotheyalign。
#包含
# include//headerfileneededtousesetw
using namespace std;
int main () )
{
int num1=2897,num3=837,num4=34,num9=12;
//Display the first row of numbers
coutsetw(6) num1 setw(6)6) num2 setw(6)6) num3 endl;
//Display the second row of numbers
coutsetw(6) num4 setw(6)6) num5 setw(6)6) num6 endl;
//Display the third row of numbers
coutsetw(6) num7 setw(6)6) num8 setw(6)6) num9 endl;
返回0;
}
程序输出结果:
2897 5 837
34 7 1623
390 3456 12
请注意,程序第三行中的#include命令已命名了新的头文件iomanip。 此文件必须包含在使用setw的程序中。
请注意,setw操作符与每个值一起使用。 这是因为setw只为后续值设置一个字段宽度。 打印此值时,cout将恢复默认打印方法。 如果数字太大,字段不能完全容纳,那会怎么样? 如下文所示:
value=18397;
coutsetw(2) value;
在这种情况下,cout打印整个数字。 这是因为setw只指定了打印字段中的最小位置数。 需要大于指定最小值的字段的数字将由cout复盖setw值。
可以为任何类型的数据指定字段宽度。 以下程序显示了与整数、浮点数和字符串对象一起使用的setw。
//thisprogramdemonstratesthesetwmanipulator
//beingusedwithvariablesofvariousdatatypes。
#包含
# include//headerfileneedtousesetw
# include//headerfileneedtousestringobjects
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;
返回0;
}
程序输出结果:
(3928 ) )。
(91.5 ) )。
(Jill Q. Jones )
这个步骤说明几个要点。
浮点数的字段宽度包含小数点的位置。
字符串的字段宽度包括字符串中的所有字符,包括空格。
默认情况下,此字段中打印的值右对齐。 也就是说,它与打印字段的右侧对齐,并根据需要在值之前包含空格。
总结
如果你觉得编程主页的内容不错,欢迎向程序员朋友推荐程序员网站。
此文字内容由网友互联网收集整理提供,仅供学习参考,版权归原作者所有。
小编个人微信号jb51ccc
喜欢与人分享编程技术和工作经验,欢迎来到编程之家官方交流群!