C++ Input Output

How can we perform Input and Output in C++ ?

 

std::cout

Data is going out ( << ) from your program to the console

Printing data to the console

std::cin

We read data from input device into ( >> ) the program.

int age;
std::cin >> age;

NOTE – std::cin — truncates reading data once it encounters a space or newline character.

Chaining input streams to read multiple data items at once

int age;
std::string name;

std::cout << "Please type in your last name and age, separated by spaces : " << std::endl;
std::cin >> name >> age;  // Raghu 35

Reading data with spaces

If you want to read data that contains spaces, then we need to use std::getline() function.

syntax :

std::getline(<input_stream>, <variable>);
std::string full_name;
std::getline(std::cin, full_name); // now we can read data that contains spaces.

Example program :