Getting last char sent to std::cout

限于喜欢 提交于 2019-12-23 03:15:21

问题


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.

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.


回答1:


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
}

And expected output:

ala ma kota

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

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

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;
};



回答2:


Instead of printing to cout, you could define your own stream-like object that accepts the standard ostream operators/functions, but keeps track of the most recently printed character as it passes the operations on to the real cout.



来源:https://stackoverflow.com/questions/12060581/getting-last-char-sent-to-stdcout

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!