Input and Output in C++
In C++, input means taking data from the user and output means displaying the result on the screen. For input, we use cin and for output, we use cout. Both cin and cout are part of the iostream library.
Header File Required
To use cin and cout, we must include the following header file:
#include <iostream>
using namespace std;
Output in C++ (cout)
cout is used to show messages, values, and results on the screen. It uses the << (insertion operator).
Syntax:
cout << data;
Example:
#include <iostream>
using namespace std;
int main() {
cout << "Welcome to ShikshaSanchar!";
return 0;
}
Output
Welcome to ShikshaSanchar!
Explanation
- cout prints data on the screen.
- << sends the data to the output stream.
Input in C++ (cin)
cin is used to take input from the user. It uses the >> (extraction operator).
Syntax:
cin >> variable;
Example:
#include <iostream>
using namespace std;
int main() {
int age;
cout << "Enter your age: ";
cin >> age;
cout << "You entered: " << age;
return 0;
}
Output
Enter your age: 20
You entered: 20
Explanation
- User enters a value, and cin stores it in the variable.
- >> extracts data from input and sends it to the variable.
- cout displays the entered value.
Taking Multiple Inputs
We can take multiple values in a single line using cin.
int a, b;
cin >> a >> b;
Explanation
- Both values can be entered together (example: 10 20).
- First value goes to a and second to b.
Using endl and \\n
We use endl or \\n to move the cursor to the next line.
cout << "Hello" << endl;
cout << "World" << "\\n";
Difference
- endl → moves to next line and clears the output buffer.
- \\n → only moves to next line.
Complete Example of Input and Output in C++
The following program takes multiple inputs from the user, uses both endl and \n, and displays the output in a clean format.
#include <iostream>
using namespace std;
int main() {
string name;
int age;
double marks;
// Taking inputs
cout << "Enter your name: ";
cin >> name;
cout << "Enter your age: ";
cin >> age;
cout << "Enter your marks: ";
cin >> marks;
// Displaying outputs using endl and \n
cout << endl; // New line using endl
cout << "----- Student Details -----\n"; // New line using \n
cout << "Name: " << name << "\n";
cout << "Age: " << age << endl;
cout << "Marks: " << marks << endl;
return 0;
}
Output:
Enter your name: Kanha
Enter your age: 20
Enter your marks: 92.5
----- Student Details -----
Name: Kanha
Age: 20
Marks: 92.5
Explanation:
- cin is used to take multiple inputs like name, age, and marks.
- endl moves to the next line and flushes the output buffer.
- \n also moves to the next line but without flushing the buffer.
- The program finally displays all the entered details in a clean format.
Summary:
- cout → used to display output.
- cin → used to take input.
- << → insertion operator (used with cout).
- >> → extraction operator (used with cin).
- endl and \\n → used for next line.
- Both belong to the iostream library.