温馨提示×

c++中cout怎么输出默认字段宽度

c++
小亿
101
2024-01-19 00:36:54
栏目: 编程语言

在C++中,可以使用setw()函数来设置cout的默认字段宽度。setw()函数位于<iomanip>头文件中,它接受一个整数参数,用于设置字段宽度。例如,下面的代码将cout的默认字段宽度设置为10个字符:

#include <iostream>
#include <iomanip>

int main() {
    std::cout << std::setw(10) << "Hello" << std::endl;
    std::cout << std::setw(10) << "World" << std::endl;
    return 0;
}

输出结果:

     Hello
     World

在上面的例子中,setw(10)cout的默认字段宽度设置为10个字符,因此输出的字符串被填充到10个字符宽度的字段中。

0