0
0
C++programming~5 mins

Using cin for input in C++

Choose your learning style9 modes available
Introduction

We use cin to get information from the user while the program is running. It helps the program learn what the user wants.

When you want the user to type their name.
When you need numbers from the user to do math.
When you want to ask the user a question and get their answer.
When you want to make the program interactive.
When you want to read multiple pieces of information one after another.
Syntax
C++
std::cin >> variable;

std::cin reads input from the keyboard.

The >> operator sends the input into the variable.

Examples
This reads an integer number from the user and stores it in age.
C++
int age;
std::cin >> age;
This reads a word (no spaces) from the user and stores it in name.
C++
std::string name;
std::cin >> name;
This reads a decimal number from the user and stores it in price.
C++
double price;
std::cin >> price;
Sample Program

This program asks the user to type their name and age. Then it says hello using the information typed.

C++
#include <iostream>
#include <string>

int main() {
    std::string name;
    int age;

    std::cout << "Enter your name: ";
    std::cin >> name;

    std::cout << "Enter your age: ";
    std::cin >> age;

    std::cout << "Hello, " << name << "! You are " << age << " years old." << std::endl;
    return 0;
}
OutputSuccess
Important Notes

cin stops reading at the first space, so it reads only one word for strings.

To read a full line with spaces, use std::getline(std::cin, variable); instead.

If the user types the wrong type (like letters when a number is expected), the program may not work as expected.

Summary

cin is used to get input from the user.

Use >> to send input into variables.

It works well for simple inputs like numbers and single words.