问题
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