Input / output

C++ uses the data stream model for input and output. The data stream for this is handled in its own library. Data streams are responsible for the transport of the data. To be able to use inputs and outputs, the input and output library iostream must be implemented at the beginning of the program code.

The simplest screen output is handled in C++ as follows: cout << "some output";

To store screen input in variables use the following command: cin >> variable-name;

Output in C++

Code Explanation

LineDescription
5Declares and initializes the variables a and b of the type integer with the values 4 and 6
7Outputs the string “Output “ (without line break)
8Outputs the string “stream” (with line break)
9Outputs the string “new line” (with line break)
10Outputs the string “new line” (with line break)
11Calculation in the output stream: variable a is added to b
12another output stream that prints the string “Number: 6”. Values and variables can be represented with << in a string.
#include &lt;iostream&gt;
using namespace std;

int main(){
    int a = 4, b = 6;

    cout << "Output ";
    cout << "stream" << endl;
    cout << "new line" << endl;
    cout << "new line\n";
    cout << a + b << endl;
    cout << "Number: " << 6;
    return 0;
}
Output
Output stream
new line
new line
10
Number: 6

Mixed Example

Code Explanation

LineDescription
5Declares and initializes the variable named integerVariable of type integer with the value 0
7Prompts the user to enter a number
8The cin object is used to accept input from the standard input device, i.e. the keyboard. The user input is then stored in the variable integerVariable
11Outputs integerVariable, chained to the string “Entered number: “
#include &lt;iostream&gt;
using namespace std;

int main () {
    int integerVariable = 0;

    cout << "Please enter a number: " << endl;
    cin >> integerVariable; // read in variable

    // variable output
    cout << "Entered number: " << integerVariable << endl;
}
Output
Please enter a number: 
12
Entered number: 12

Multiple Inputs

#include &lt;iostream&gt;
using namespace std;

int main () {
    int x;
    char c;

    cout << "Please enter an integer followed by a character: " << endl;
    cin >> x >> c; // read in variable

    // variable output
    cout << "Integer: " << x << "\nCharacter: " << c << endl;
}
Output
Please enter an integer followed by a character: 
5
z
Integer: 5
Character: z