【问题标题】:How to output non null terminated string to iostream, but keep formatting如何将非空终止字符串输出到 iostream,但保持格式化
【发布时间】:2018-07-06 00:36:04
【问题描述】:

我正在尝试输出非空终止字符串,但保持 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 上失败。

【问题讨论】:

  • return os &lt;&lt; std::string(sr.data(), sr.size());?
  • 你可能对std::string_view感兴趣。
  • @Someprogrammerdude 是的,并即时创建字符串,包括 malloc ... StringRef 是我自己的 string_view 实现
  • 来自链接的参考:“......将每个字符......存储到输出流 os 中,就像调用os.rdbuf()-&gt;sputn(seq, n)一样”。带有前导双下划线的符号为编译器和标准库保留,它们应被视为不可移植。链接的参考还描述了如何处理填充和字段宽度。如果您跳过哨兵对象的创建,它是一个详细的列表,您可以将其逐字复制到您自己的代码中。如果你这样做了,那么它是可移植的。
  • @Nick 我没有看到任何迹象表明std::string_view 进行了任何内存分配。

标签: c++ iostream


【解决方案1】:

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

我确实打开了 GCC C++ 库代码并从那里“偷走”了。清理后的代码是这样的:

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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多