Open In App

cout in C++

Last Updated : 13 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In C++, cout is an object of the ostream class that is used to display output to the standard output device, usually the monitor. It is associated with the standard C output stream stdout. The insertion operator (<<) is used with cout to insert data into the output stream.

Let’s take a look at an example:

C++
#include <iostream>
using namespace std;

int main() {
    
      // Print standard output
    // on the screen
    cout << "Welcome to GFG";

    return 0;
}

Output
Welcome to GFG

Syntax of cout

cout << var_name;

Here,

  • <<: It is the insertion operator used to insert data into cout.
  • var_name: It represents the variable or literal whose value you want to display.

Examples of cout in C++

The below programs demonstrate how to use the cout for output purposes in C++.

Print Hello World

C++
#include <iostream>
using namespace std;

int main() {

    // Printing hello world using cout
    cout << "Hello, World!";

    return 0;
}

Output
Hello, World!

Displaying Multiple Variables

C++
#include <iostream>
using namespace std;

int main() {
    int n = 42;
    string s = "The answer is ";

      // Printing both n and s
    cout << s << n;
  
    return 0;
}

Output
The answer is 42

cout Member Functions in C++

Below is a list of some commonly used member functions of cout in C++:

Member FunctionDescription
cout.put(char)Writes a single character to the output stream.
cout.write(char*, int)Writes a block of characters from the array to the output stream.
cout.precision(int)Sets the decimal precision for displaying floating-point numbers.
cout.setf(ios::fmtflags)Sets the format flags for the stream.
cout.width(int)Sets the minimum field width for the next output.
cout.fill(char)Sets the fill character for padding the field.

Below is the implementation of the member functions of the cout.write() and cout.put():

C++
#include <iostream>
using namespace std;

int main() {
    char s[] = "Welcome at GFG";
    char c = 'e';

    // Print first 6 characters
    cout.write(s, 6);

    // Print the character c
    cout.put(c);
  
    return 0;
}

Output
Welcome

Below is the C++ program to illustrate the use of cout.precision():

C++
#include <iostream>
using namespace std;

int main() {
    double pi = 3.14159783;

    // Set precision to 5
    cout.precision(5);

    cout << pi << endl;

    // Set precision to 7
    cout.precision(7);

    cout << pi << endl;

    return 0;
}

Output
3.1416
3.141598


Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg
  翻译: