温馨提示×

如何设置c++的setfill

c++
小樊
84
2024-08-11 04:02:36
栏目: 编程语言

在C++中,可以使用setfill函数来设置填充字符。setfill函数位于<iomanip>头文件中,用于设置setw函数中指定的宽度不足时要使用的填充字符。

以下是一个示例代码,演示如何使用setfill函数设置填充字符:

#include <iostream>
#include <iomanip>

int main() {
    int num = 123;

    std::cout << "Default width and fill character:" << std::endl;
    std::cout << std::setw(10) << num << std::endl;

    std::cout << "Set width and fill character:" << std::endl;
    std::cout << std::setfill('*') << std::setw(10) << num << std::endl;

    return 0;
}

在上面的示例中,首先输出默认情况下的宽度为10的填充字符为空格。然后使用setfill函数将填充字符设置为*,再次输出相同的宽度为10,此时填充字符为*

输出结果如下:

Default width and fill character:
       123
Set width and fill character:
*******123

通过这种方式,可以灵活地设置填充字符以满足不同的输出需求。

0