Output

In C++, output is typically handled using the output stream objects that are part of the C++ Standard Library. The most commonly used output stream object is cout, which stands for "character output stream." It is used to display output to the standard output device, which is usually the console or terminal.

Basic Syntax for Output in C++

The basic syntax for using std::cout to output data is as follows:

#include <iostream> using namespace std; int main() { cout << "Hello, World!"; return 0; }

In this example, the << operator is the insertion or "put to" operator, and it writes the string "Hello, World!" to the standard output (usually the console).

Outputting Variables

You can also output the value of variables:

#include <iostream> using namespace std; int main() { int x = 42; cout << "The value of x is: " << x; return 0; }

Formatting Output

C++ allows for more advanced output formatting using manipulators. For example, you can set the precision for floating-point numbers:

#include <iostream> #include <iomanip> using namespace std; int main() { double pi = 3.141592653589793; cout << setprecision(4); cout << pi; // Output will be 3.142 return 0; }

Multiple Insertions

You can chain multiple insertions together in a single statement:

Newlines and Other Special Characters

Special characters like newline (\n) and tab (\t) can also be used:

Summary

  • cout is used for outputting text and variables to the console.

  • The << operator is used to insert data into the output stream.

  • Output can be formatted using various methods and manipulators.

  • Special characters like newline and tab can be used for formatting.

 

COSC-1336 / ITSE-1302 Computer Science - Author: Dr. Kevin Roark