Namespaces
Variants

operator<< (std::basic_string_view)

From cppreference.net
定义于头文件 <string_view>
template < class CharT, class Traits >

std:: basic_ostream < CharT, Traits > &
operator << ( std:: basic_ostream < CharT, Traits > & os,

std:: basic_string_view < CharT, Traits > v ) ;
(C++17 起)

表现为一个 格式化输出函数 。在构造并检查哨兵对象后, 确定输出格式的填充方式

然后将结果序列 seq (包含填充内容的 v )中的每个字符存储到输出流 os ,如同调用 os. rdbuf ( ) - > sputn ( seq, n ) ,其中 n std:: max ( os. width ( ) , str. size ( ) )

最后,调用 os. width ( 0 ) 以取消 std::setw 的效果(如果存在的话)。

目录

异常

若输出期间抛出异常,则可能抛出 std::ios_base::failure

参数

os - 字符输出流
v - 待插入的视图

返回值

os

示例

#include <iomanip>
#include <iostream>
#include <string_view>
int main()
{
    constexpr std::string_view s{"abc"};
    constexpr int width{5};
    // fill/left/right 属性在更改前保持不变
    std::cout << std::setfill('-');
    std::cout << std::left;
    std::cout << '[' << std::setw(width) << s << "]\n";
    std::cout << '[' << std::setw(width) << s << "]\n";
    std::cout << std::right;
    std::cout << '[' << std::setw(width) << s << "]\n";
    // width 在每次调用后重置
    std::cout << '[' << s << "]\n";
}

输出:

[abc--]
[abc--]
[--abc]
[abc]

参见

对字符串执行流输入和输出操作
(函数模板)