We use multiple input and output to handle several pieces of information at once. This helps us work with more data in one go.
0
0
Multiple input and output in C++
Introduction
When you want to read a person's name and age together.
When you need to get multiple numbers from the user to calculate their sum.
When you want to print several results at once, like scores of different players.
When you want to input and output multiple values in a single line for convenience.
Syntax
C++
std::cin >> var1 >> var2 >> var3; std::cout << val1 << ' ' << val2 << ' ' << val3 << std::endl;
You can use the extraction operator (>>) multiple times to read several inputs in one line.
Use the insertion operator (<<) multiple times to print multiple outputs together.
Examples
This reads two integers and prints them separated by a space.
C++
int a, b; std::cin >> a >> b; std::cout << a << ' ' << b << std::endl;
This reads two words as names and prints them in reversed order with a comma.
C++
std::string firstName, lastName;
std::cin >> firstName >> lastName;
std::cout << lastName << ", " << firstName << std::endl;This reads three decimal numbers and prints their sum.
C++
double x, y, z;
std::cin >> x >> y >> z;
std::cout << x + y + z << std::endl;Sample Program
This program asks the user to enter their name and age in one line. Then it greets the user with their name and age.
C++
#include <iostream> #include <string> int main() { int age; std::string name; std::cout << "Enter your name and age: "; std::cin >> name >> age; std::cout << "Hello, " << name << ". You are " << age << " years old." << std::endl; return 0; }
OutputSuccess
Important Notes
When reading strings with spaces, std::cin stops at the first space. Use std::getline() if you want to read full lines.
Make sure the input matches the expected types to avoid errors.
Summary
You can read multiple inputs in one line using multiple >> operators.
You can print multiple outputs in one line using multiple << operators.
This makes your program simpler and faster when handling several values.