Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the best way to print to the console in c++?

Tags:

c++

I have read three ways to print things to the console in c++ from various sources.

  1. Using using namespace std; and then using cout (CodeBlocks Standard)
  2. Not using the above and using std::cout and std::endl; (C++ Primer)
  3. Using printf (HackerRank)

Which is preferred and why?

like image 656
Devesh Lohumi Avatar asked Jun 13 '18 10:06

Devesh Lohumi


People also ask

What is used to write or display to console in C++?

A modern console consists of the keyboard and a window on a computer screen. cin (console in), cout (console out), and cerr (console error) are stream objects that become part of every C++ program. The console objects channel streams of bytes to and from running programs.

What is the command used to print a string on console?

To print a String to console output, you can use System. out. print() or System.

Where does printf print to in C?

The printf function formats and prints a series of characters and values to the standard output stream, stdout .


1 Answers

Number 2 with amendment. (std::cout and '\n')

Why?

  1. Because you should avoid using namespace std. Source
  2. (Among other reasons) Because cout is typesafe and printf is not. Source
  3. std::endl will force a flush of the output buffer to the console. Unless you specifically want this to happen use << '\n' or << "...string\n". Source
like image 191
Fantastic Mr Fox Avatar answered Oct 22 '22 19:10

Fantastic Mr Fox