Print time with every call to std :: cout

How will someone do this? For example, I like:

std::cout << "something";

then he must print the time before "something"

+3
source share
4 answers

You can use a simple function that prints a timestamp and then returns a stream for further printing:

std::ostream& tcout() {
  // Todo: get a timestamp in the desired format
  return std::cout << timestamp << ": ";
}

Then you called this function instead of using it directly std::coutwhenever you inserted a timestamp:

tcout() << "Hello" << std::endl;
+4
source

Create your own thread for this: This should work:

class TimedStream {
public:
    template<typename T>
    TimedStream& operator<<(const T& t) {
        std::cout << getSomeFormattedTimeAsString() << t << std::endl;
        return *this;
    }
};

TimedStream timed_cout;

void func() {
    timed_cout << "123";
}

You can use this class for each type for which it std::cout << objcan be performed, so no further work is required.

, <<, . :

class TimestampDummy {} timestamp;

ostream& operator<<(ostream& o, TimestampDummy& t) {
    o << yourFancyFormattedTimestamp();
}

void func() {
    cout << timestamp << "123 " << 456 << endl;
}
+6

. - :

std::cout << time << "something";

. < < /.

0
ostream& printTimeWithString(ostream& out, const string& value)
{
  out << currentTime() << ' ' << value << std::endl;
  return out;
}

, Boost.DateTime.

0

Source: https://habr.com/ru/post/1774995/


All Articles