在 C++ 中使用 setw Manipulator

这篇文章展示了如何在 C++ 中使用 setw 流操作器。

在 C++ 中使用 std::setw 函数修改下一个 I/O 操作的宽度

流操纵器是修改输入/输出格式的特殊对象,有时会生成一些动作。std::endl 函数可以说是输出流中最常用的对象,它确实是一个流操纵器。它打印一个换行符并刷新输出缓冲区。

另一方面,std::setw 命令不会产生任何输出。相反,它将下一个 I/O 的宽度设置为传递的整数参数。一些流操纵器使用参数;这些必须包含一个 <iomanip> 标题。以下示例演示了 setw 操纵器的基本输出格式设置方案。setfill 机械手是 setw 的天然伴侣。前者对于使用给定的 char 参数修改填充字符很有用。

#include <sstream>#include <iostream>#include <iomanip>using std::cout; using std::setw;
using std::endl; using std::string;
int main() {
    cout << "setw() : |" << 11 << "|" << endl
          << "setw(4): |" << setw(4) << 11 << "|" << endl
          << "setw(4): |" << 22
          << setw(4) << std::setfill('-') << 22 << 33 << "|" << endl;
    return EXIT_SUCCESS;
}

输出:

setw() : |11|
setw(4): |  11|
setw(4): |22--2233|

或者,我们可以使用 setw 操作符来限制从 stringstream 对象中提取的字符数。此方法可能对声明为固定数组的 char 缓冲区有用。通常,操纵器是使用函数重载来实现的。

每个操纵器都是返回对流的引用的函数。指向这些函数之一的指针被传递给流提取/插入运算符,这些运算符本身就是重载运算符。参数函数是从重载运算符的主体中调用的。

#include <sstream>#include <iostream>#include <iomanip>using std::cout; using std::setw;
using std::endl; using std::string;
int main() {
    std::stringstream ss1("hello there");
    char arr[10];
    ss1 >> setw(6) >> arr;
    cout << arr;
    return EXIT_SUCCESS;
}

输出:

hello

setw 操纵器的一个有用功能是轻松设置需要存储在固定大小缓冲区中的用户输入的限制。我们只需要将 sizeof(buffer) 作为参数传递给 setw。请注意,setw 调用会影响单个 I/O 操作,然后会自动恢复默认宽度。相反,setfill 修改保持活动状态,直到显式更改。

#include <iostream>#include <iomanip>using std::cout; using std::setw;
using std::endl; using std::cin;
int main() {
    char buffer[24];
    cout << "username: ";
    cin >> setw(sizeof(buffer)) >> buffer;
    return EXIT_SUCCESS;
}

输出:

username: