捕获和格式化cout

Capturing and formatting cout

本文关键字:cout 格式化      更新时间:2023-10-16

如何捕获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的单独实例