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?

asked Jun 5 by dtivl (2,500 points)

1 Answer

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;


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


$ 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

#include <iostream>

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

Built and run it:

$ g++ -o s && ./s
hello world!
answered Jun 5 by dtivl (2,500 points)

Please log in or register to answer this question.

Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost