Lesson 18 +10 XP

User Input with cin

User Input with cin

Programs get exciting when they listen. That's cin's job: read what the user types.

The basics

#include <iostream>
using namespace std;

int main() {
    int x;
    cout << "Type a number: ";
    cin >> x;
    cout << "The number you typed is " << x << endl;
    return 0;
}
  • The user types a number and presses Enter.
  • cin >> x grabs the value and stores it in the variable x. The arrow points toward x.

It works for many types

cin >> extracts a value that matches the variable's type:

double price;
cin >> price;   // reads a decimal like 9.99

int, double, float - they all work.

Reading several values

You can chain inputs in one statement:

int a, b;
cout << "Type two numbers: ";
cin >> a >> b;
cout << "Sum: " << a + b << endl;

The user can type 3 4 (space-separated) and both numbers land in a and b.

Reading text

For words, add the <string> header and read into a string:

#include <string>
string name;
cin >> name;

Extraction notes

  • cin >> skips leading whitespace automatically.
  • It reads until whitespace for a single token, so cin >> name grabs just the first word.
  • When the type doesn't match (like typing "abc" into an int), input stops matching - later lessons cover handling that gracefully.

TL;DR

  • cin >> x; stores what the user typed into x.
  • Works for numbers and decimals: int, double, float.
  • Read several at once: cin >> a >> b;.
  • Add <string> and use string for words.