C++

C++ cout: Usage and Examples

arage.com@gmail.com

cout is an object that refers to the standard output stream included in the C++ standard library, and it stands for “console output”.

It primarily provides a method for a program to display messages to the user. Generally, it is used to output strings, numbers, etc. to the console screen (terminal or command prompt).

Usage of cout

How to Include cout in a Program

To use cout in your program, you need to include the iostream library of C++. This is done as follows:

1#include <iostream>

Then, specify cout using the std namespace:

1std::cout << "Hello, World!";

Basic Output of Strings

The basic way to output strings in C++ is as follows:

1#include <iostream>
2
3int main() {
4    std::cout << "Hello, World!";
5    return 0;
6}

Outputting Special Characters and Symbols

How to Output Quotation Marks

To output double quotation marks (“), use the escape character (backslash \). Here is an example:

1std::cout << "He said, \"Hello, World!\"";

How to Output Backslashes

To output the backslash itself, use two consecutive backslashes. Here is an example:

1std::cout << "This is a backslash: \\";

Comparison of cout and Other Output Methods

The Difference between cout and printf

The main difference between cout and the C language printf is that cout provides C++ type safety and can use overloaded insertion operators (<<). This allows you to define the output method of your types. On the other hand, while printf uses format strings, it is prone to type mismatches and other issues.

Detailed Behavior and Settings of cout

Synchronization of cout and stdout

By default, cout and C’s standard output (stdout) are synchronized, ensuring compatibility. However, this can cause a slight decrease in performance. If necessary, you can disable synchronization:

1std::ios_base::sync_with_stdio(false);

Flushing Operation of cout

cout is buffered, and it is output when a certain amount of data accumulates. If you want to output immediately, you can flush (force output) using endl:

1std::cout << "Immediate output" << std::endl;

Usage of Manipulators to Control cout Behavior

What is a Manipulator?

A manipulator is a special function that manipulates streams. This allows you to control the format of the output (such as precision, fill, field width, etc.).

Examples of Using Manipulators

For example, to set the number of decimal places when outputting a floating-point number, use std::setprecision:

1#include <iostream>
2#include <iomanip>  // Header file required to use manipulators
3
4int main() {
5    double pi = 3.14159265;
6    std::cout << std::setprecision(4) << pi;  // Outputs "3.142"
7    return 0;
8}

Thus, by using cout and manipulators, it is possible to meticulously control the output in C++.

記事URLをコピーしました