Standard input and output

Output

We output values to standard output (the screen) using the std::cout command and the << operator:

#include <iostream>
int main(){
	std::cout << "Hello World!" << std::endl;
	int x = 123;
	std::cout << "The value of x is: " << x << std::endl;
}

Input

We can accept values from the standard input using the std::cin function and the >> operator.

#include <iostream>
int main(){
	int x;
	std::cout << "Enter the value of x: ";
	std::cin >> x;
	std::cout << "The value you entered is  " << x << std::endl;
}

We can accept multiple values using multiple >> operators:

#include <iostream>
int main(){
	int x, y, z;
	std::cout << "Enter the value of x, y and z separated by space: ";
	std::cin >> x >> y >> z;
	std::cout << "x is: " << x << " y is: " << y << " z is: " << z << std::endl;
}

We can input multiple values of different types using one std::cin command:

#include <iostream>
int main(){
	int x;
	double d;
	char c;
	std::cout << "Enter the value of x, d and c separated by space: ";
	std::cin >> x >> d >> c;
	std::cout << "x is: " << x << " d is: " << d << " c is: " << c << std::endl;
}

The above statement of std::cin >> x >> d >> c; is equivalent of multiple std::cin statements:

std::cin >> x;
std::cin >> d;
std::cin >> c;

String input

When inputting a string we use the std::getline function in combination with std::cin:

#include <iostream>
#include <string>
int main(){
	std::string tempstring;
	std::cout << "Enter the string: ";
	std::getline(std::cin, tempstring);
	std::cout << "You entered: " << tempstring;