Most programs are more useful when they can respond to the person running them. A calculator that only adds 5 + 3 is a bit pointless — you want to tell it what numbers to add. That’s where user input comes in.
In C++, the primary way to read input from the keyboard is withcin. This tutorial explains how it works, where it trips people up, and how to handle common input scenarios.
The Basics: Reading a Single Value#
cinstands forcharacter inputand is part of the<iostream>library. You use it with the>>operator (the extraction operator).
Here’s a minimal 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; }CopyRun this, type25, press Enter, and you’ll see:
Enter your age: 25 You are 25 years old.CopyThe>>operator extracts the typed value and stores it inage. That’s the core of howcinworks.
Reading Different Data Types#
cinis smart enough to handle different variable types — it converts the input automatically based on the type of variable you’re reading into.
#include <iostream> using namespace std; int main() { int count; double price; char grade; cout << "Enter item count: "; cin >> count; cout << "Enter price: "; cin >> price; cout << "Enter grade (A/B/C): "; cin >> grade; cout << "Count: " << count << ", Price: $" << price << ", Grade: " << grade << endl; return 0; }CopyThe key point:cinreadswhitespace-delimited tokens. It skips leading spaces and stops at the next space, tab, or newline. That behaviour is fine for single words and numbers, but it becomes a problem with strings containing spaces.
Reading Strings: Where cin Falls Short#
Try this:
#include <iostream> #include <string> using namespace std; int main() { string name; cout << "Enter your name: "; cin >> name; cout << "Hello, " << name << "!" << endl; return 0; }CopyIf you typeJohn Smith, onlyJohngets stored inname. The wordSmithis left sitting in the input buffer waiting for the nextcin >>.
To read a full line including spaces, usegetline:
#include <iostream> #include <string> using namespace std; int main() { string name; cout << "Enter your full name: "; getline(cin, name); cout << "Hello, " << name << "!" << endl; return 0; }CopyNowJohn Smithis stored in full.
Reading Multiple Values at Once#
You can chain the>>operator to read several values in one statement:
#include <iostream> using namespace std; int main() { int x, y; cout << "Enter two numbers: "; cin >> x >> y; cout << "Sum: " << x + y << endl; return 0; }CopyThe user can type10 20on one line (space-separated) or press Enter after each number —cinhandles both.
The cin + getline Mixing Problem#
This trips up almost every beginner at some point. Watch what happens when you usecin >>beforegetline:
#include <iostream> #include <string> using namespace std; int main() { int age; string name; cout << "Enter your age: "; cin >> age; cout << "Enter your name: "; getline(cin, name); // This gets skipped! cout << "Age: " << age << ", Name: " << name << endl; return 0; }CopyWhen you type25and press Enter,cin >> agereads25but leaves the\n(the newline from pressing Enter) in the input buffer.getlinethen picks up that leftover newline and immediately returns with an empty string.
The fix: addcin.ignore()aftercin >>and beforegetline:
cin >> age; cin.ignore(); // Discard the leftover newline getline(cin, name);CopyOr more robustly:
cin >> age; cin.ignore(numeric_limits<streamsize>::max(), '\n'); getline(cin, name);CopyThis discards everything up to and including the next newline. Once you understand why this happens, it makes complete sense.
A Practical Example: Simple Calculator#
Let’s put it together in a small program that actually does something useful:
#include <iostream> using namespace std; int main() { double a, b; char op; cout << "Enter calculation (e.g. 5 + 3): "; cin >> a >> op >> b; cout << a << " " << op << " " << b << " = "; if (op == '+') cout << a + b; else if (op == '-') cout << a - b; else if (op == '*') cout << a * b; else if (op == '/') { if (b != 0) cout << a / b; else cout << "Error: division by zero"; } else { cout << "Unknown operator"; } cout << endl; return 0; }CopyEnter calculation (e.g. 5 + 3): 10 * 4 10 * 4 = 40CopyBasic Input Validation#
cinsets a fail state if the input doesn’t match the expected type. For example, if you ask for anintand the user typeshello,cinfails and stops working until you clear the error.
Here’s how to handle that:
#include <iostream> using namespace std; int main() { int number; cout << "Enter a number: "; while (!(cin >> number)) { cout << "That's not a valid number. Try again: "; cin.clear(); // Clear the error flag cin.ignore(1000, '\n'); // Discard the bad input } cout << "You entered: " << number << endl; return 0; }Copycin.clear()resets the error state, andcin.ignore()throws away the invalid characters so the next read starts fresh.
Common cin Mistakes (and Fixes)#
Forgetting to include<iostream>cinis defined there. Without it, you’ll get a compilation error.
Usingcinwithout>>on the right variable type
If your variable isintbut the user types a decimal like3.7,cinreads3and leaves.7in the buffer for the next read.
Not usinggetlinefor strings with spaces
Usecin >> wordfor single words; usegetline(cin, line)for whole sentences.
Forgettingcin.ignore()betweencin >>andgetline
Always add it when mixing the two.
Discover more
keyboard
Input Devices
Books & Literature
If you're looking to go deeper with C++, the C++ Better Explained Ebook is perfect for you — whether you're a complete beginner or looking to solidify your understanding. Just $19.
Reading Input in a Loop#
A common pattern is to keep reading input until the user signals they’re done:
#include <iostream> using namespace std; int main() { int total = 0; int num; cout << "Enter numbers to add (type 0 to stop):" << endl; while (cin >> num && num != 0) { total += num; } cout << "Total: " << total << endl; return 0; }CopyThewhile (cin >> num && num != 0)checks two things: that the read succeeded, and that the value isn’t the sentinel (0).
Discover more
Software Utilities
Programming
Book
Quick Reference#
| Task | Code |
|---|---|
| Read an integer | cin >> num; |
| Read a double | cin >> price; |
| Read a single word | cin >> word; |
| Read a full line | getline(cin, line); |
| Read multiple values | cin >> a >> b >> c; |
| Clear after bad input | cin.clear(); cin.ignore(1000, '\n'); |
| Fix cin + getline mixing | cin.ignore();between them |
Discover more
Computer Keyboards
keyboard
Software Utilities
Related Articles#
- C++ Variables and Data Types — the types you’ll be storing input into
- C++ Loops Tutorial — combine with input for interactive programs
- C++ Conditionals Tutorial — act on what the user types
- C++ Functions Tutorial — wrap your input logic in reusable functions
- C++ String Handling — more on working with text in C++
Take Your C++ Further#
If you’re looking to go deeper with C++, theC++ Better Explained Ebookis perfect for you — whether you’re a complete beginner or looking to solidify your understanding. Just$19.
👉Get the C++ Better Explained Ebook — $19