如何将非空终止字符串输出到 iostream,但保持格式化

How to output non null terminated string to iostream, but keep formatting

我正在尝试输出非空终止字符串,但保留 iomanip 格式,例如std::left、std::setw等

我当前的代码如下所示:

inline std::ostream& operator << (std::ostream& os, const StringRef &sr){
    //return os.write(sr.data(), sr.size() );
    // almost the same, but std::setw() works
    return __ostream_insert(sr.data(), sr.size() );
}

使用 gcc 在 Linux 上运行正常,但使用 clang 在 MacOS 上运行失败。

关于os.rdbuf()->sputn(seq, n)的建议当然很有趣,但没有达到预期的效果。

我确实打开了 GCC C++ 库代码并从那里 "stole"。清理后,代码是这样的:

inline std::ostream& operator << (std::ostream& os, const StringRef &sr){
    // following is based on gcc __ostream_insert() code:
    // https://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.2/ostream__insert_8h-source.html

    std::streamsize const width = os.width();
    std::streamsize const size  = static_cast<std::streamsize>( sr.size() );
    std::streamsize const fill_size = width - size;

    bool const left = (os.flags() & std::ios::adjustfield) == std::ios::left;

    auto osfill = [](std::ostream& os, auto const count, char const c){
        for(std::streamsize i = 0; i < count; ++i)
            os.put(c);
    };

    if (fill_size > 0 && left == false)
        osfill(os, fill_size, os.fill());

    os.write(sr.data(), size);

    if (fill_size > 0 && left == true)
        osfill(os, fill_size, os.fill());

    return os;
}