C++设置场宽总结

前言

我在百度上搜了好久,关于C++如何设置场宽这一块,要么就是过于分散,要么就是晦涩难懂。今天我就来弥补这个空缺。

场宽是什么

场宽指在输出时每个输出项所占的长度。若输出项的长度大于场宽则输出的结果是那个输出项不受场宽限制,后面的输出项仍然在其后输出。

设置场宽的几个函数

setw()

使用这个函数记得加头文件< iomanip> 。
使用方法为cout<< setw(场宽)<<输出项。

#include
#include
using namespace std;
int a[3][3]={{-1,0,1},{0,1,10,},{1,-10,1}};
int main()
{
    for (int i=0;i<3;i++)
    {
        for (int j=0;j<3;j++) 
        {
            cout<5)<cout<<'\n';
    }
}

输出结果为

   -1    0    1
    0    1   10
    1  -10    1

可以看出,默认情况下,setw()函数是右对齐的。数字加上前面的空格是5格,即场宽。值得一提的是,setw()仅能控制下一次输出。
那要左对齐怎么办?cout<< left<< setw(场宽)<<输出项。
右对齐也可以写成cout<< right<< setw(场宽)<<输出项。
效果如下:

#include
#include
using namespace std;
int a[3][3]={{-1,0,1},{0,1,10,},{1,-10,1}};
int main()
{
    for (int i=0;i<3;i++)
    {
        for (int j=0;j<3;j++) 
        {
            cout<5)<cout<<'\n';
    }
}

输出:

-1   0    1
0    1    10
1    -10  1

printf

这个用起来很方便。
头文件自然是< cstdio>。
用法:printf(“%场宽d”,输出项);是整数才在场宽后写d。
实现如下:

#include
#include
using namespace std;
int a[3][3]={{-1,0,1},{0,1,10,},{1,-10,1}};
int main()
{
    for (int i=0;i<3;i++)
    {

        for (int j=0;j<3;j++) 
        {
            printf("%5d",a[i][j]);
        }
        cout<<'\n';
    }
}

输出:

   -1    0    1
    0    1   10
    1  -10    1

这也是右对齐的。如果要左对齐,在场宽前加个负号就好了。看程序:

#include
#include
using namespace std;
int a[3][3]={{-1,0,1},{0,1,10,},{1,-10,1}};
int main()
{
    for (int i=0;i<3;i++)
    {

        for (int j=0;j<3;j++) 
        {
            printf("%-5d",a[i][j]);
        }
        cout<<'\n';
    }
}

输出:

-1   0    1
0    1    10
1    -10  1

cout.width()

写程序时,我们主要使用setw()函数和printf,这个函数只是了解一下就行了。
用法:cout.width(场宽);cout<<输出项;
头文件是< iostream>
具体实现看程序:

#include
#include
using namespace std;
int a[3][3]={{-1,0,1},{0,1,10,},{1,-10,1}};
int main()
{
    for (int i=0;i<3;i++)
    {

        for (int j=0;j<3;j++) 
        {
            cout.width(5);
            cout<cout<<'\n';
    }
}

输出:

   -1    0    1
    0    1   10
    1  -10    1

由此可得,这个函数也是右对齐。这个函数也只是控制下一次输出。

总结

一般前两个用得比较多,个人觉得printf比较方便。虽然总结得可能有些不全,但尽我所知全都写在上面了。有什么还需要讲得更详细的,也希望大家多多指出。

你可能感兴趣的:(C++设置场宽总结)