[英]Using C++ fmtlib, is there a cleaner way to append a sequence of data to a string than using std::ostringstream?
The fmtlib package provides a clean, readable and fast way to format string data in C++, but I cannot find a clean and readable way to use it to append a sequence of data to a string. fmtlib软件包提供了一种干净,易读且快速的方式来格式化C ++中的字符串数据,但是我找不到一种干净易读的方式来使用它来将数据序列附加到字符串上。
After much googling, I've come up with a working solution, but it is much more verbose than using the typical approach of std streams and chevrons. 经过大量的搜索之后,我想出了一个可行的解决方案,但是比使用标准的std流和V形人字形更为冗长。 I can't any/many examples of this using fmtlib, so I'm hoping some expert out there knows a neater way of doing this.
我无法使用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;
}
I'm just dumping an array of ints to stdout to look like this: [0]=2 [1]=0 [2]=0 [3]=0 [4]=1 [5]=0 [6]=0 [7]=0 我只是将一个int数组转储到stdout看起来像这样:[0] = 2 [1] = 0 [2] = 0 [3] = 0 [4] = 1 [5] = 0 [6] = 0 [7] = 0
You can write to the output stream directly without an intermediate buffer: 您可以直接写入输出流而无需中间缓冲区:
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");
}
Note that you don't need to cast dataline[jj]
to int
, because unlike iostreams, {fmt} correctly handles uint8_t
. 请注意,您不需要将
dataline[jj]
为int
,因为与iostreams不同,{fmt}可以正确处理uint8_t
。
If you want to build a string you can either write to a memory_buffer
or pass back_insert_iterator
to format_to
. 如果要构建字符串,则可以写入
memory_buffer
或将back_insert_iterator
传递给format_to
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.