Input and Output
NOTE: This article is part of a C++ guide, therefore only C++ code will be displayed.
Standard Input / Output
To interact with the user through the console we need to include a library. The library we will use in this case is <iostream>
. This means that from now on the structure of a program should look like this:
#include <iostream>
using namespace std;
int main(){
// our code goes here
}
Output
When outputing some text to the standard out(also known as stdout) we can use the following syntax:
cout << thing << endl;
here thing
represents any data we want to output (be it a string, variable, number, etc.)
here endl
represents the new line character "\n"
, meaning the following line is equivalent:
cout << thing << "\n";
We can output multiple things by adding more <<
operators:
cout << thing1 << thing2 << thing3 << "\n";
These can also be separated into multiple lines like this:
cout << thing1;
cout << thing2;
cout << thing3;
cout << "\n";
or any combination:
cout << thing1
cout << thing2 << thing3;
cout << "\n";
Input
Input is similar in syntax to cout
, but the operators go in reverse(i.e. cout has <<
, cin has >>
).
Example:
int num;
int x;
cin >> num;
cin >> x;
int num;
int x;
cin >> num >> x;
The values gotten from stdin have to be separated by white space. This means that the following inputs would be valid for the shown example:
1 2
1 2
1
2
Example program
#include <iostream>
using namespace std;
int main() {
int a,b;
int c;
cin >> a;
cin >> b >> c;
cout << "The sum of these three numbers is " << a + b + c << endl;
int multiplied_numbers = a * b * c;
cout << "The multiplication of these three numbers is ";
cout << multiplied_numbers << "\n";
}