std::setw(n)的作用是设置输出宽度为n,默认为右对齐,并且用空格填充。
例如:cout << std::setw(5) << "0" << "1" << endl,该语句就是设置字符串"0"的输出宽度为5,默认为右对齐,空格填充。
若想使用其他符号填充(例如用'*'填充),则可以用cout << std::setw(5) << setfill('*') << "0" << "1" << endl;
如果想修改成左对齐,则只需要在std::setw(n)之前加上std::left即可。
当要输出的字符串宽度大于setw设置的宽度n时,直接输出想要输出的字符串即可(此时忽视setw设置的宽度)。
通过运行如下测试代码即可了解setw()的规则:
#include <iomanip>
#include <iostream>
#include<string.h>
using namespace std;
int main()
{
/*默认为右对齐,此时加不加std::right都可以 */
cout << std::setw(5) << "0" << "1" << endl;
cout << std::setw(5) << "00" << "1" << endl;
cout << std::setw(5) << "000" << "1" << endl;
/*用<<left或者std::left改成左对齐*/
cout << std::left << std::setw(5) << "0" << "1" << endl;
cout << std::left << std::setw(5) << "00" << "1" << endl;
cout << std::left << std::setw(5) << "000" << "1" << endl;
/*当要输出的字符串宽度大于setw设置的宽度时,直接输出想要输出的字符串即可*/
cout << std::right <<std::setw(5) << "0000000" << "1" << endl;
/*用其他符号填充*/
cout << std::right <<std::setw(5) << setfill('*') << "0" << "1" << endl;
cout << std::left << std::setw(5) << setfill('*') << "0" << "1" << endl;
return 0;
}
代码运行结果: