0
0
C++programming~5 mins

Input and output using cin and cout in C++

Choose your learning style9 modes available
Introduction

We use cin to get information from the user and cout to show information on the screen.

When you want to ask the user to type their name.
When you need to get numbers from the user to do math.
When you want to show messages or results to the user.
When you want to make a simple interactive program.
When you want to read and write data in a console application.
Syntax
C++
#include <iostream>
using namespace std;

int main() {
    int number;
    cout << "Enter a number: ";
    cin >> number;
    cout << "You entered: " << number << endl;
    return 0;
}

cout is used with the << operator to send output to the screen.

cin is used with the >> operator to get input from the user.

Examples
This example asks the user for their age and then shows it back.
C++
#include <iostream>
using namespace std;

int main() {
    int age;
    cout << "Enter your age: ";
    cin >> age;
    cout << "Your age is " << age << endl;
    return 0;
}
This example gets a single word name from the user and greets them.
C++
#include <iostream>
#include <string>
using namespace std;

int main() {
    string name;
    cout << "Enter your name: ";
    cin >> name;
    cout << "Hello, " << name << "!" << endl;
    return 0;
}
This example reads a decimal number and shows it with a dollar sign.
C++
#include <iostream>
using namespace std;

int main() {
    double price;
    cout << "Enter price: ";
    cin >> price;
    cout << "Price is $" << price << endl;
    return 0;
}
Sample Program

This program asks the user to enter two numbers, adds them, and shows the result.

C++
#include <iostream>
using namespace std;

int main() {
    int num1, num2;
    cout << "Enter first number: ";
    cin >> num1;
    cout << "Enter second number: ";
    cin >> num2;
    int sum = num1 + num2;
    cout << "Sum is: " << sum << endl;
    return 0;
}
OutputSuccess
Important Notes

Use cin carefully: if the user types the wrong type (like letters instead of numbers), it can cause errors.

To read a full line with spaces, use getline(cin, variable) instead of cin >> variable.

Summary

cin gets input from the user.

cout shows output to the screen.

Use << with cout and >> with cin.