获取最后一个字符发送到std :: cout [英] Getting last char sent to std::cout

查看:142
本文介绍了获取最后一个字符发送到std :: cout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在main()执行结束时检查最后一个字符是否发送到stdout(通过 std :: cout \\ n'(或平台特定的行尾)。如何测试这个?可以安全地假设没有使用C风格io(如printf)。

I need at the end of main() execution to check if last char sent to stdout (through std::cout) was '\n' (or platform specific end-of-line). How to test for this? It is safe to assume that C style io (like printf) was not used.

程序是C ++的REPL。它评估C ++表达式(或语句)并在stdout上打印结果。

Program is REPL for C++. It evaluates C++ expressions (or statements) and prints results on stdout. It is desirable that output would be always terminated with single new-line.

推荐答案

这是由@Kevin给出的类似的答案。但我相信它更适合你的需要。而不是使用一些你的流代替cout - 你可以用你自己的std :: cout替换streambuf:

It is similar answer to this given by @Kevin. However I believe it is better for your needs. Instead of using some your stream in place of cout - you can replace streambuf from std::cout with your own:

int main() {
   std::streambuf* cbuf = std::cout.rdbuf(); // back up cout's streambuf
   std::cout.flush();
   keep_last_char_outbuf keep_last_buf(cbuf);
   std::cout.rdbuf(&keep_last_buf);          // assign your streambuf to cout

   std::cout << "ala ma kota\n";

   char last_char = keep_last_buf.get_last_char();
   if (last_char == '\r' || last_char == '\n')
      std::cout << "\nLast char was newline: " << int(last_char) << "\n";
   else
      std::cout << "\nLast char: '" << last_char << "'\n";

   std::cout << "ala ma kota";
   last_char = keep_last_buf.get_last_char();
   if (last_char == '\r' || last_char == '\n')
      std::cout << "\nLast char was newline: " << int(last_char) << "\n";
   else
      std::cout << "\nLast char: '" << last_char << "'\n";

   std::cout.rdbuf(cbuf); // restore cout's original streambuf
}

预期输出:

ala ma kota

Last char was newline: 10
ala ma kota
Last char: 'a'

写一个任务 class keep_last_char_outbuf 不是很容易,查找装饰器模式和 streambuf 界面。

A task to write such class keep_last_char_outbuf is not very easy, Look for decorator pattern and streambuf interface.

如果你没有时间玩这个 - 看看我的建议 ideone链接

If you don't have time for playing with this - look at my proposal ideone link

class keep_last_char_outbuf : public std::streambuf {
public:
    keep_last_char_outbuf(std::streambuf* buf) : buf(buf), last_char(traits_type::eof()) {
        // no buffering, overflow on every char
        setp(0, 0);
    }
    char get_last_char() const { return last_char; }

    virtual int_type overflow(int_type c) {
        buf->sputc(c);
        last_char = c;
        return c;
    }
private:
    std::streambuf* buf;
    char last_char;
};

这篇关于获取最后一个字符发送到std :: cout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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