Input and Output in C++
Programs become meaningful only when they can interact with users. This interaction is done through input and output.
In this lesson, you will learn how C++ displays output on the screen
and how it receives input from the user using cout and cin.
These concepts are used in almost every real-world C++ application.
Understanding Input and Output
Input refers to data provided to a program while it is running. Output refers to information produced by the program after processing.
C++ provides standard input and output streams that make this interaction simple and efficient.
Displaying Output Using cout
The cout object is used to display output on the screen.
It belongs to the standard output stream.
The insertion operator << sends data to the output stream.
#include <iostream>
using namespace std;
int main() {
cout << "Welcome to C++";
return 0;
}
This program prints the message Welcome to C++ on the screen.
Printing Multiple Values
You can print text, numbers, and variables together by chaining the insertion operator.
int score = 95;
cout << "Your score is " << score;
The output appears in the same order as written in the statement.
Using endl for New Lines
By default, output remains on the same line.
To move output to a new line, C++ provides the endl keyword.
It also flushes the output buffer, ensuring output is displayed immediately.
cout << "Hello" << endl;
cout << "C++";
This results in output appearing on two separate lines.
Taking Input Using cin
The cin object is used to read input from the keyboard.
It stores the entered value inside a variable.
The extraction operator >> is used with cin.
int age;
cin >> age;
Here, the value entered by the user is stored in the variable age.
Combining Input and Output
Most programs use input and output together. Let us look at a complete example.
#include <iostream>
using namespace std;
int main() {
int age;
cout << "Enter your age: ";
cin >> age;
cout << "You are " << age << " years old." << endl;
return 0;
}
This program reads user input and displays it back in a formatted way.
Common Mistakes to Avoid
- Forgetting to include
<iostream> - Using
cinwithout declaring variables - Entering text when a number is expected
- Missing semicolons at the end of statements
Practice Exercise
- Write a program that asks for a user’s name
- Ask for the user’s age
- Display both values on separate lines
Quick Quiz
Question 1:
Which object is used to display output in C++?
Answer: cout
Question 2:
Which operator is used with cin?
Answer: The extraction operator >>
Question 3:
What does endl do?
Answer: Moves output to a new line and flushes the output buffer.
What’s Next?
In the next lesson, you will learn about variables and constants and how data is stored in C++ programs.