iostream

iostream is a header file that is part of the standard C++ library. It is part of the input/output library. iostream is short for input-output stream.

In C++, if you wish to provide input and output, we need to use iostream. With iostream we gain input and output services, which we can use by using different objects. Two of these are cout and cin.

syntax

#include <iostream>

There are four objects in the iostream header:

  • cin
    reads from the standard C input stream stdin

  • cout
    writes to the standard C output stream stdout

  • cerr
    writes to the standard C error stream stderr, unbuffered

  • clog
    writes to the standard C error stream stderr

cin

cin is an object and is short for character input.

syntax

#include <iostream>

int main()
{
string yourName;
    std::cout << "Please enter your name: ";
    std::cin >> yourName;
    std::cout << "\n" << "Your name is: " << yourName;
}

Here I have created a variable of type string, to store the input entered by the user. You write cin, followed by the extraction operator (>>), followed by the variable.

This is the result of running the program and entering Matthew:

cout

cout is an object and is short for character output. cout allows us to output characters to the console.

syntax

#include <iostream>

int main()
{
std::cout << "Hello world";
}

Here I have used cout to output Hello world. You write cout, followed by the insertion operator (<<), followed by the text in double quotes.

This is the result of running the program:

cout iostream c++
Figure 1. using cout
#include <iostream>

int main()
{
    string firstName = "Bill";
    string secondName = "Gates";
    std::cout << firstName << " " << secondName;
}

Here I have created 2 variables, of type string, to store 2 names. Then I wrote cout, followed by the insertion operator (<<), followed by the first variable, an insertion operator, followed by a space, followed by a further insertion operator, followed by the second variable. You can use as many insertion operators as you wish. Each one concatenates itself to the next. You will also see that you can place variables directly into the stream.

This is the result of running the program:

Since we can place variables directly into the stream, we can perform arithmetic in the stream with (and without) variables:

#include <iostream>

int main()
{
    int numberOne = 10;
    int numberTwo = 23;
    std::cout "numberOne + numberTwo = " << numberOne + numberTwo;
}