天天看点

setw(n)和setfill()使用

使用setw(n)设置输出宽度时,默认为右对齐,如下:

std::cout << std::setw(5) << "1" << std::endl;

std::cout << std::setw(5) << "10" << std::endl;

std::cout << std::setw(5) << "100" << std::endl;

std::cout << std::setw(5) << "1000" << std::endl;

输出结果:

//

// 1

// 10

// 100

// 1000

若想让它左对齐的话,只需要插入 std::left,如下:

std::cout << std::left << std::setw(5) << "1" << std::endl;

std::cout << std::left << std::setw(5) << "10" << std::endl;

std::cout << std::left << std::setw(5) << "100" << std::endl;

std::cout << std::left << std::setw(5) << "1000" << std::endl;

输出结果:

1

10

100

1000

同理,右对齐只要插入 std::right,不过右对齐是默认状态,不必显式声明。

注意:setw()默认填充的内容为空格,可以setfill()配合使用设置其他字符填充。

cout<<setfill('*')<<setw(5)<<'a'<<endl;

则输出:

****a //4个*和字符a共占5个位置。

参考:https://zhidao.baidu.com/question/530113273.html

https://www.cnblogs.com/zhizhan/p/3822494.html