如何实现ostream
-like类从零开始使用printf
只?
对我来说貌似问题是在选择格式字符串,这实际上等于确定input`s型和治疗精度ostream实现使用printf
-1
A
回答
1
我假定你的意思是,通过“一个ostream
般的类”重载operator<<
。仅通过重载就可以很容易地识别函数的参数类型。例如,您可能有:
ostreamlike& ostreamlike::operator<<(int x)
{
printf("%d", x);
return *this;
}
ostreamlike& ostreamlike::operator<<(float x)
{
printf("%f", x);
return *this;
}
输出的格式取决于选择哪个超载。
0
这取决于你想要接近真实的ostream
。假设你想正确地做到这一点,你还需要一个streambuf
派生类。 ostream
只做格式化,实际的I/O由内部的streambuf
派生类完成。由于streambuf
没有格式化的I/O,因此您需要使用fwrite
而不是printf
。
如果您的目标只是在已有的FILE*
指针上进行I/O操作,那么这就是要走的路。你从streambuf
派生出一个班级,说streambuf_with_FILE
,然后你从ostream
派生出另一个班级,说ostream_with_FILE
。 streambuf_with_FILE
将覆盖相应的方法来执行实际的I/O并且ostream_with_FILE
有一个内部的streambuf_with_FILE
对象。实际上只需要很少的代码。
1
认为,这可能是类似的东西
#include <stdio.h>
class ostreamlike {
public:
ostreamlike(FILE* f_): f(f_) {}
ostreamlike& write(int n) {
fprintf(f, "%d", n);
return *this;
}
ostreamlike& write(const char* n) {
fprintf(f, "%s", n);
return *this;
}
private:
FILE* f;
};
// operator for types that is supported ostreamlike internally
template <typename type>
ostreamlike& operator<<(ostreamlike& stream, const type& data) {
return stream.write(data);
}
// external implementations to write using ostreamlike
ostreamlike& operator<<(ostreamlike& stream, bool data) {
return stream.write(data ? "true" : "false");
}
int main() {
ostreamlike s(stdout);
s << "hello " << 1 << " : " << true << "\n";
return 0;
}
相关问题
- 1. 如何实现'虚拟ostream&print(ostream&out)const;'
- 2. 如何将C++ std :: ostream与printf-like格式一起使用?
- 3. OCJP - 在java中实现printf
- 4. Printf和Scanf C++的实现
- 5. 如何查看printf的实现源?
- 6. 有.net的printf的免费实现吗?
- 7. 如何在printf中实现'include'?
- 8. sprintf或printf的最小实现
- 9. 有没有办法使用“ostream”来写入std :: string的现有实例
- 10. 使用%。 in printf
- 11. 在C++或库中是否存在null std :: ostream实现?
- 12. Printf出现负数
- 13. 放弃现有的printf语句,使新加入的printf语句
- 14. C++ ostream引用
- 15. printf使用堆栈?
- 16. 的printf使用%d
- 17. 不使用printf()的
- 18. 使用printf函数
- 19. 使用。*在printf中
- 20. “&”使用printf()和scanf()
- 21. 为什么`std :: common_type_t <std :: ostream&,std :: ostream&>`等于`std :: ostream`而不是`std :: ostream&`?
- 22. rfind实现使用发现
- 23. 使用ServiceStack实现多个ICacheClient实现
- 24. JMS使用Scala实现队列实现
- 25. 使用Subversion实现SCM实现ClearCase
- 26. C++ ostream的最佳实践(tostring)
- 27. 实现(使用HTML)
- 28. 实现使用BNF
- 29. 实现使用jQuery
- 30. 使用RESTClient实现