C++中setfill,setw,setbase,setprecision 函数用来控制输出格式的操纵符。

使用的时候需要引入:#include <iomanip>

具体的功能:

std::setfill:设置std::setw将填充什么样的字符 如:std::setfill('*'),默认情况下,填充字符是空格(’ ')

std::setw :需要填充多少个字符,默认填充的字符为' '空格

std::setbase(n):将输出[数据转换]为n进制,n只能为8,10,16;

std::setprecision():控制输出流显示[浮点数]的数字个数,C++默认的流输出数值有效位是6。 std::left 左对齐

std::right 右对齐 样例

填充x ,设置总的长度为8

setfill 和 setw

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

int main() 
{
    int num =12;
    cout << setfill('x') << setw(8) << num <<endl; // 打印结果 xxxxxx12
    cout <<left<< setfill('x') << setw(8) << num <<endl; // 打印结果 12xxxxxx
    cout <<right<< setfill('x') << setw(8) << num <<endl; // 打印结果 xxxxxx12
    return 0;
}

setbase

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

int main() 
{
    int num =12;
    //打印8进制
    cout << setbase(8) << num <<endl; // 打印结果14
    //打印10进制
    cout << setbase(10) << num <<endl;
    //打印16进制
    cout << setbase(16) << num <<endl; //打印结果c
    return 0;
}

setprecision

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

int main() 
{
    double num =3.1415926;
    //保留1位数
    cout << setprecision(1) << num <<endl; //打印结果3
    //保留2位数
    cout << setprecision(2) << num <<endl; //打印结果3.1
    //保留4位数
    cout << setprecision(4) << num <<endl; //打印结果3.142
    return 0;