How to print a line to STDERR and STDOUT in C++?

In C++, how to print a string as a line to STDOUT? That is, the string and the newline character, nicely?

And similarly, how to print the line to STDERR?

In C++, you may print the string and then 'n' or std::endl to STDOUT by operating on the std::cout stream:

std::cout << your_string << std::endl;

or

std::cout << your_string << 'n';

Example:

$ cat a.cpp
#include <iostream>

int main()
{
  std::cout << "hello world!" << std::endl;
  std::cout << "happy Dtivl!" << 'n';
  return 0;
}

$ g++ a.cpp -o a && ./a
hello world!
happy Dtivl!

In C++, std::cerr is a stream to the STDERR.

You can use the common I/O operators like << or std::cerr to print content to the STDERR.

One example is in stderr.cc:

#include <iostream>

int main()
{
  std::cerr << "hello world!n";
}

Built and run it:

$ g++ stderr.cc -o s && ./s
hello world!
Answered by dtivl.

3 comments:

  1. Title should be “How to print a line to stderr OR stdout in C++?” as I was looking for how to print to both at the same time.

    1. I guess the “and” in the title should be the “and” in “buy an apple and a banana” rather than the “&&” in “a && b” ;-)

      If you want to print to STDOUT && STDERR **atomically**, it will be an interesting problem. The operations of printing a line to STDOUT or STDERR themselves are not atomic operations.

      One way that is close to that may be to use a producer/consumer like printing mechanism:

      – one buffer using an array like data structure for holding each item/line to be printed out and 2 status marks for each item
      – 2 threads waiting for the buffer content and print them to STDOUT and STDERR each; after prints it, the thread sets that corresponding buffer status
      – 1 cleaner thread to clean the items if both statuses are set

      The printing function writes the item/line to be printed out to the buffer.

      The outputs to STDERR and STDOUT may run in parallel though not strictly synchronized or atomically.

Leave a Reply

Your email address will not be published. Required fields are marked *