◐ Shell
clean mode source ↗

std::basic_ostream<CharT,Traits>::put - cppreference.com

来自cppreference.com

basic_ostream& put( char_type ch );

表现为无格式输出函数 (UnformattedOutputFunction) 。构造并检查 sentry 对象后,将字符 ch 写入输出流。

若输出因任何原因失败,则设置 badbit

参数

返回值

*this

注解

不同于有格式的 operator<<,此函数不对 signed charunsigned char 类型重载。

不同于有格式输出函数,若输出失败,则此函数不设置 failbit

示例

#include <fstream>
#include <iostream>

int main()
{
    std::cout.put('a'); // 正常用法
    std::cout.put('\n');

    std::ofstream s("/does/not/exist/");
    s.clear(); // 假装流是好的
    std::cout << "未格式化输出: ";
    s.put('c'); // 这将设置 badbit ,但非 failbit
    std::cout << " fail=" << bool(s.rdstate() & s.failbit);
    std::cout << " bad=" << s.bad() << '\n';
    s.clear();
    std::cout << "格式化输出:   ";
    s << 'c'; // 这将设置 badbit 和 failbit
    std::cout << " fail=" << bool(s.rdstate() & s.failbit);
    std::cout << " bad=" << s.bad() << '\n';
}

输出:

a
未格式化输出:  fail=0 bad=1
格式化输出:    fail=1 bad=1

参阅