跳转至

格式控制

1 引言

本文主要讲述输出时作格式控制的相关内容。

2 std::setw(int n)

std::setw(int n)是 C++ 在输出操作中使用的字段宽度设置,设置输出的域宽,n表示字段宽度。

只对紧接着的输出有效,紧接着的输出结束后又变回默认的域宽。当后面紧跟着的输出字段长度小于n的时候,在该字段前面用空格补齐;当输出字段长度大于n时,全部整体输出。

示例程序:

#include <iostream>
#include <iomanip>
using namespace std;
int main() {
    string s = "Study";
    cout << s << endl;
    cout << setw(10) << s << endl;
    return 0;
}

输出结果:

Study     
     Study

3 std::fixed + std::setprecision(int n)

如果一个数字太大,无法使用std::setprecision(int n)指定的有效数位数来打印,则许多系统会以科学表示法的方式打印。

std::setprecision(int n) 将指定浮点数字的小数点后要显示的位数,而不是要显示的总有效数位数,一般和std::fixed结合起来用。

示例程序:

#include <iostream>
#include <iomanip>
using namespace std;
int main() {
    double num = 1145141919810;
    cout << num << endl;
    cout << fixed << num << endl;
    cout << fixed << setprecision(2) << num << endl;
    return 0;
}

输出结果:

1.14514e+12
1145141919810.000000
1145141919810.00