Another reason why printf() is better than std::cout

As I am working on a client / server system, I was printing out some info to see where I was getting stuck and noticed that all the messages got mangled really bad.

I was using statements such as:

std::cerr << "got message: "
          << message_name << "\n";

The problem with the implementation of cerr is that it actually prints each part one by one. This means the console gets locked and unlocked many times (which is slow!) and another process may write in between each one of your message chunk.

This is where a printf() is better since it creates one string and then prints it out as one chunk. This means one lock, one unlock, and especially, one sensible line in your console.

That being said, I bared printf() in my software, since the format is dificult to keep straight, and also since we are using Qt we have the ability to use a QString() format which is a lot better (i.e. it uses positional arguments only; so no type.)

This allows me to rewrite the previous statement as:

std::cerr << QString("got message: %1\n")

(we also have a small header to allow QString in the std::cerr without the need to use toStdString(), which is not UTF-8 compatible!)

Now the output may get intermixed, but each line is pure instead of all mangled.