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.

Leave a Reply

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