使用 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++ 使用 ostringstream std      更新时间:2023-10-16

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_bufferback_insert_iterator传递给format_to