命名空间
变体
操作

std::setw

来自 cppreference.cn
< cpp‎ | io‎ | manip
 
 
 
输入/输出操纵器
浮点格式化
整数格式化
布尔格式化
字段宽度和填充控制
setw
其他格式化
空白字符处理
输出刷新
(C++20)  

状态标志操作
时间与金钱 I/O
(C++11)
(C++11)
(C++11)
(C++11)
带引号的操纵器
(C++14)
 
定义于头文件 <iomanip>
/* 未指定 */ setw( int n );

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

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

目录

[编辑] 参数

n - 宽度的新值

[编辑] 返回值

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

  • 如果 out 是类型为 std::basic_ostream<CharT, Traits> 的对象,则表达式 out << setw(n)
    • 的类型为 std::basic_ostream<CharT, Traits>&
    • 值为 out
    • 其行为如同调用了 f(out, n)
  • 如果 in 是类型为 std::basic_istream<CharT, Traits> 的对象,则表达式 in >> setw(n)

其中函数 f 定义为

void f(std::ios_base& str, int n)
{
    // set width
    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::ostreamstd::istream
可用于任何
字符流

[编辑] 另请参阅

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