c++ - 如何将非空终止字符串输出到 iostream,但保持格式化
问题描述
我正在尝试输出非空终止字符串,但保持 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++ 库代码并从那里“偷走”了。清理之后,代码是这样的:
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;
}
推荐阅读
- javascript - d3.format 1 个十进制加字母 X
- reactjs - React Native undefined 不是一个对象(评估'HomeScreen.props.navigation')
- mysql - 如何通过终端在mysql中连续上传文件的整个文本
- android - 尝试为空活动运行 Android Studio 模拟器时出错
- python - 在完全执行完成之前结束scrapy runpider
- html - 禁用字体真棒图标上的颜色
- python - 为什么 Python/Python 如何知道在 pub.publish() 定义后执行回调函数?
- java - 如何设置 setter 和 getter 以通过测试用例。Ceasar 密码类型问题
- symfony4 - 在 symfony 4 中使用 ManyToMany 插入数据
- javascript - 用reactjs制作前端网站后如何添加django后端?