Namespaces
Variants

std:: setw

From cppreference.net
< cpp ‎ | io ‎ | manip
定义于头文件 <iomanip>
/* 未指定 */ setw ( int n ) ;

当在表达式 out << std :: setw ( n ) in >> std :: setw ( n ) 中使用时,将流 out in width 参数精确设置为 n

某些操作会将宽度重置为零(参见 下文 ),因此可能需要重复调用 std::setw 来为多个操作设置宽度。

目录

参数

n - 宽度的新值

返回值

一个未指定类型的对象,使得

其中函数 f 定义为:

void f(std::ios_base& str, int n)
{
    // 设置宽度
    str.width(n);
}

备注

流的宽度属性将在调用以下任一函数时重置为零(意为"未指定"):

  • 输入
  • 输出

该修饰符对输入和输出产生的具体效果因各个I/O函数而异,并在每个 operator << operator >> 重载页面上分别进行说明。

示例

#include <iomanip>
#include <iostream>
#include <sstream>
int main()
{
    std::cout << "no setw: [" << 42 << "]\n"
              << "setw(6): [" << std::setw(6) << 42 << "]\n"
              << "no setw, several elements: [" << 89 << 12 << 34 << "]\n"
              << "setw(6), several elements: [" << 89 << std::setw(6) << 12 << 34 << "]\n";
    std::istringstream is("hello, world");
    char arr[10];
    is >> std::setw(6) >> arr;
    std::cout << "Input from \"" << is.str() << "\" with setw(6) gave \""
              << arr << "\"\n";
}

输出:

no setw: [42]
setw(6): [    42]
no setw, several elements: [891234]
setw(6), several elements: [89    1234]
Input from "hello, world" with setw(6) gave "hello"

缺陷报告

以下行为变更缺陷报告被追溯应用于先前发布的C++标准。

缺陷报告 应用于 发布时行为 正确行为
LWG 183 C++98 setw 仅能用于类型为
std::ostream std::istream 的流
可用于任意
字符流

参见

管理字段宽度
( std::ios_base 的公开成员函数)
更改填充字符
(函数模板)
设置填充字符的位置
(函数)
控制是否使用前缀指示数值进制
(函数)