获取stdout内容而不禁用cout / cin [英] Getting stdout contents without disabling cout/cin

查看:192
本文介绍了获取stdout内容而不禁用cout / cin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以将终端(先前)写入的内容(stdout)保存到字符串数组:

Is it possible to save terminal (previously) written contents (stdout), to an array of strings:

vector<string> lines;



<在一个linux控制台应用程序中。

without disabling cin/cout normal functionality, in a linux console application.

在终端窗口中,除了字符,还有每个字符的着色信息。是否有办法将它们保存在另一个数组中?

In a terminal window in addition to characters there's coloring information for each character. Is there a way to save them in another array?

推荐答案

如果你想在程序中写< $ c> std :: cout ,并且数据出现在终端和一些程序内部数据结构中,您将使用自定义流缓冲区。这里我们看一个简单的例子:

If you mean you want to write inside a program to std::cout and have the data appear both on the terminal and in some program-internal data structure, you would use a custom stream buffer. Here us a simple example of how this would look:

#include <streambuf>
#include <iostream>

struct capturebuf
    : std::streambuf
{
    std::ostream&   d_out;
    std::streambuf* d_sbuf;
    std::string&       d_str;
public:
    capturebuf(std::ostream& out, std::string& str)
        : d_out(out)
        , d_sbuf(out.rdbuf())
        , d_str(str)
    {
        out.rdbuf(this);
    }
    ~capturebuf() {
        this->d_out.rdbuf(this->d_sbuf);
    }
    int overflow(int c) {
        if (c != std::char_traits<char>::eof()) {
            this->d_str.push_back(c);
        }
        return this->d_sbuf->sputc(c);
    }
    int sync() { return this->d_sbuf->pubsync(); }
};

上面的流缓冲区只是添加每个写入字符串的字符。字符也被转发到传递的流缓冲区。需要转发到 pubsync(),以确保基础流在适当的时间刷新。

The above stream buffer will just add each character written to the string referenced during construction. The characters are also forwarded to the passed stream buffer. The forwarding to pubsync() is needed to make sure the underlying stream is flushed at the appropriate times.

实际上使用它,你需要将它安装到 std :: cout 。因为 capturebuf 的构造函数和析构函数已经执行了注册/注销,所以它需要构造一个相应的对象:

To actually use it, you need to install it into std::cout. Since the constructor and destructor of capturebuf already do the registration/deregistration, all it takes is to construct a corresponding object:

int main()
{
    std::string capture;
    {
        capturebuf buf(std::cout, capture);
        std::cout << "hello, world\n";
    }
    std::cout << "caught '" << capture << "'\n";
}

这段代码不太符合你的要求,只需要不同地处理换行符。完全缺少的是缓冲,这是不需要获得功能,而是获得性能。以上是在移动设备上输入的,可以证明是充斥着打字错误,但方法应该照常工作。

This code doesn't quite do what you asked but nearly: you'd just need to process newlines differently. What is entirely missing is buffering which isn't needed to get the functionality but to get the performance. The above was typed in on a mobile device and is provably riddled with typos but the approach should work as is.

这篇关于获取stdout内容而不禁用cout / cin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆