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;
Line | Description |
---|---|
5 | Declares and initializes the variables a and b of the type integer with the values 4 and 6 |
7 | Outputs the string “Output “ (without line break) |
8 | Outputs the string “stream” (with line break) |
9 | Outputs the string “new line” (with line break) |
10 | Outputs the string “new line” (with line break) |
11 | Calculation in the output stream: variable a is added to b |
12 | another output stream that prints the string “Number: 6”. Values and variables can be represented with << in a string. |
#include <iostream>
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 stream
new line
new line
10
Number: 6
Line | Description |
---|---|
5 | Declares and initializes the variable named integerVariable of type integer with the value 0 |
7 | Prompts the user to enter a number |
8 | The 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 |
11 | Outputs integerVariable , chained to the string “Entered number: “ |
#include <iostream>
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;
}
Please enter a number:
12
Entered number: 12
#include <iostream>
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;
}
Please enter an integer followed by a character:
5
z
Integer: 5
Character: z