使用 C++ fmtlib,有没有比使用 std::ostringstream 更干净的方法来将数据序列附加到字符串中
Using C++ fmtlib, is there a cleaner way to append a sequence of data to a string than using std::ostringstream?
fmtlib 包提供了一种干净、可读且快速的方法来格式化 C++ 中的字符串数据,但我找不到一种干净且可读的方式来使用它将数据序列附加到字符串中。
经过多次谷歌搜索,我想出了一个可行的解决方案,但它比使用 std 流和 V 形的典型方法要冗长得多。我不能使用 fmtlib 提供任何/很多例子,所以我希望那里的一些专家知道一种更简洁的方法。
// Here is an fmtlib version of dump_line. I don't like it. using 'cout' seems cleaner and simpler.
virtual void dump_line( const char* msg, uint8_t* dataline )
{
fmt::memory_buffer out;
format_to(out, "{} :", msg);
for( int jj=0; jj<m_cacheStore.p_LineSize; jj++) {
format_to(out, " [{}]={}", jj, (int)dataline[jj] );
}
fmt::print("{}n",fmt::to_string(out) );
}
// Here is the typical approach using cout and chevrons.
// Nice and simple.
virtual void dump_line( const char* msg, uint8_t* dataline )
{
cout << msg << " : " ;
for( int jj=0; jj<m_cacheStore.p_LineSize; jj++)
cout << " [" << jj << "]=" << (int)dataline[jj];
cout<<endl;
}
我只是将一系列整数转储到 stdout 中,如下所示: [0
]=2 [1]=0 [2]=0 [3]=0 [4]=1 [5]=0 [6]=0 [7]=0可以直接写入输出流,而无需中间缓冲区:
virtual void dump_line(const char* msg, uint8_t* dataline) {
fmt::print("{} :", msg);
for (int jj=0; jj<m_cacheStore.p_LineSize; jj++) {
fmt::print(" [{}]={}", jj, dataline[jj]);
}
fmt::print("n");
}
请注意,您不需要将dataline[jj]
转换为int
,因为与iostreams不同,{fmt}可以正确处理uint8_t
。
如果要构建字符串,可以写入memory_buffer
或back_insert_iterator
传递给format_to
。
相关文章:
- 通过JNI传递数据数组的最快方法是什么
- 如何使用curlpp通过POST方法上传文件和json数据
- 有哪些有效的方法可以消除一组 100 万个字符串>重复数据?
- 拥有映射的现代方法,该映射可以指向或引用已在堆栈上分配的不同类型的数据
- 将线程中的数据存储到全局容器的最佳方法?
- 将复杂的非基元C++数据类型转换为 Erlang/Elixir 格式,以使用 NIF 导出方法
- 在C++中查找像素 RGB 数据的最快方法是什么?
- 构造智能点数据类型以及普通数据类型的通用方法
- 将传入的网络"char*"数据转换为"uint8_t"并返回的安全方法是什么?
- 读取大文件(>2GB)(文本文件包含以太网数据)并通过不同参数随机访问数据的最佳方法是什么?
- 在 c++ 中解析数据包数据的最佳方法是什么?
- 处理编译器关于可能丢失数据的警告的最优雅方法是什么
- 创建异构顶点数据数组的可移植方法
- 使用 memcpy 将矢量数据复制到 wstring 的正确方法
- 在 std::vector<无符号字符中存储任意数据的方法>
- 在C++事务之间存储大量字符数据的有效方法
- 学习数据结构和算法的简单方法
- C++中的多维数据集:从 std::vector 的 2D 数据到 std::vector 的 2D 网格的最干净方法?
- C++ 使用派生类方法更改基类数据成员
- 调试数据方法 Q抽象表模型