捕获和格式化cout
Capturing and formatting cout
如何捕获cout的输入?
的例子:
如果我输入:
std::cout<<"Some normal text here" << fout <<"Test %, %", 1, 2<< "works 100% fine."<<std::endl
则输出:
"一些正常的文本在这里测试1,2工作100%好。"
100%没有格式化,因为<<操作符。只有在4后面的内容才会被格式化,直到它遇到<<运营商。
我可以这样做吗?
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
std::ostream& fout (std::ostream& I)
{
//Some how format my text here.. Then return it as the ostream.
return I;
}
int main(int argc, char* argv[])
{
std::cout<< fout << "Test %", 1 << "Other stuff 20%.";
//So Anything after fout<< should be stolen and formatted then given back to cout.. Other stuff 20% isn't formatted because of the <<.
}
我知道这看起来很傻,但我真的很想知道这是怎么做到的。我看到boost通过Format("%20") % SomeVar
做了类似的事情但是我想弄清楚如何使用插入操作符和逗号操作符。有什么类似的想法吗?
您需要为您的<<
和,
操作符定义一个新的类型,以唯一地工作。
就像这样。
struct fout
{
// To establish the formatting string (returns *this)
fout& operator << ( const std::string &format_string );
// To insert data into the formatted string (returns *this)
template < typename T >
fout& operator , ( const T &data );
// To produce a type that can be sent to std::cout, etc.
operator std::string ();
};
允许这样的代码:
cout << "Normal text " << (fout() << "Test %, %", 1, 2 ) << "works";
// ^^ A fout object is being constructed here.
如果你不喜欢这些括号,重命名结构体并创建一个名为fout
的单独实例
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- std::cout.imbue()多重调用
- C++格式化输出问题
- 如何在C++中用std::cout正确显示带十六进制的字符串文本
- 为什么在C的循环中使用printf的Rust代码不显示输出,而在C++的循环中显示std::cout
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- 格式化浮点值:返回默认值
- 在作为静态成员包含在另一个类中的类的构造函数中使用 cout
- 在 COUT 语句中使用 COUT 调用函数
- GCC 4.8.2 自动矢量化由于 cout 而失败
- OpenCV格式化程序类和Mat对象的cout产生链接器错误:体系结构x86_64的未定义符号:libopencv_co
- 如何使用浮点值格式化 cout 的输出
- 在C++中格式化 Cout 输出
- 格式化指针的cout
- 用std::cout格式化二进制文字
- cout如何知道如何格式化不同的类型
- "cout"的格式化输出范围是多少
- 如何使用cout格式化输出
- 捕获和格式化cout
- 如何存储字符串,同时保留提取格式化字符串的能力(如cout)