首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >C++:如何将fprintf结果作为std::string w/o sprintf

C++:如何将fprintf结果作为std::string w/o sprintf
EN

Stack Overflow用户
提问于 2008-09-16 06:12:48
回答 7查看 39.4K关注 0票数 18

我正在使用一个用C++实现的开源UNIX工具,我需要修改一些代码才能让它实现我想要的功能。我想做最小的改变,希望我的补丁能在上游被接受。可以在标准C++中实现并且不会创建更多外部依赖项的解决方案是首选。

这就是我的问题。我有一个C++类--让我们称它为"A“--它目前使用fprintf()将其高度格式化的数据结构打印到文件指针。在它的print函数中,它还递归地调用几个成员类的相同定义的print函数("B“是一个例子)。还有另一个类C,它的成员std::string "foo“需要设置为A的实例的print()结果。可以将它看作A的to_str()成员函数。

在伪代码中:

代码语言:javascript
复制
class A {
public:
  ...

  void print(FILE* f);
  B b;

  ...  
};

...

void A::print(FILE *f)
{
  std::string s = "stuff";
  fprintf(f, "some %s", s);
  b.print(f);
}

class C {
  ...
  std::string foo;
  bool set_foo(std::str);
  ...
}

...

A a = new A();
C c = new C();

...

// wish i knew how to write A's to_str()
c.set_foo(a.to_str());

值得一提的是,C是相当稳定的,但A和B(以及A的其余依赖项)处于不断变化的状态,因此需要的代码更改越少越好。还需要保留当前的打印(FILE* F)接口。我考虑了几种实现A::to_str()的方法,每种方法都有优缺点:

  1. 将对fprintf()的调用改为

代码语言:javascript
复制
- I wouldn't have to rewrite any format strings
- print() could be reimplemented as: fprint(f, this.to\_str());
- But I would need to manually allocate char[]s, merge a lot of c strings , and finally convert the character array to a std::string

  1. 尝试在字符串流

中捕获a.print()的结果

代码语言:javascript
复制
- I would have to convert all of the format strings to << output format. There are hundreds of fprintf()s to convert :-{
- print() would have to be rewritten because there is no standard way that I know of to create an output stream from a UNIX file handle (though [this guy says it may be possible](http://synflood.at/blog/index.php?/archives/456-One-word-of-warning-about-stdio_filebuf.html)).

使用Boost的字符串format library

代码语言:javascript
复制
- More external dependencies. Yuck.
- Format's syntax is different enough from printf() to be annoying: 

printf(format_str,args) -> cout << boost::format(format_str) % arg1 % arg2 %等

使用Qt的QString::asprintf()

代码语言:javascript
复制
- A different external dependency.

那么,我是否已经用尽了所有可能的选择?如果是这样,你认为哪一个是我最好的选择?如果不是,我忽略了什么?

谢谢。

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69738

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档