User Input

User Input in C++: Items arrive on a conveyor belt, one after another, separated by little dividers. The cashier takes the next item, scans it, and moves on.

The Analogy: The Conveyor Belt at the Checkout

Items arrive on a conveyor belt, one after another, separated by little dividers. The cashier takes the next item, scans it, and moves on. They cannot skip ahead, and if a customer puts down something unexpected the belt jams.

std::cin is that belt. It is a stream: a queue of characters waiting to be read. >> takes the next item, stopping at the first divider — and in C++ the divider is any whitespace. Understanding that the belt keeps its position between reads, and that leftover items stay on it, explains almost every input bug you will ever hit.


Syntax or Core Structure

#include <iostream>

int main() {
    int x{};
    std::cout << "Type a number: ";
    std::cin >> x;
    std::cout << "Your number is: " << x << "\n";
    return 0;
}

The arrows point the way the data travels: std::cout << pushes data out to the screen, std::cin >> pulls data in to your variable.

// Several values in one statement -- read left to right
int x{}, y{};
std::cout << "Two numbers, separated by space or newline: ";
std::cin >> x >> y;
std::cout << "Sum is: " << (x + y) << "\n";
// The word-only problem
#include <string>

std::string name;
std::cout << "Full name: ";
std::cin >> name;              // types "Ada Lovelace", stores only "Ada"

std::getline(std::cin, name);  // reads the whole line, spaces included

std::cin >> name stops at the first space because whitespace is a divider. std::getline reads to the newline instead, which is what you want for anything a human types as a sentence.


Technical Depth: The Two Bugs Everyone Hits

Bug one: the leftover newline

int age{};
std::string name;

std::cout << "Age: ";
std::cin >> age;                // you type "30\n" -- reads 30, LEAVES the newline
std::cout << "Name: ";
std::getline(std::cin, name);   // sees the leftover newline, returns immediately!
// name is empty and the program never waited

>> stops before the newline, so the newline is still sitting on the belt. The next getline finds it immediately and hands you an empty string. The fix is to clear the rest of the line:

#include <limits>

std::cin >> age;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::getline(std::cin, name);   // now it waits properly

That ignore call reads and discards characters until it has consumed a newline. It looks verbose because it is being explicit about "however many characters it takes".

Bug two: the failed read

int age{};
std::cin >> age;        // user types "banana"
// The read FAILS: age stays 0, the stream enters a fail state,
// and "banana" is still on the belt. Every later read also fails instantly.

A stream that has failed stays failed until you clear it. Always check:

#include <iostream>
#include <limits>

int readInt(const std::string& prompt) {
    int value{};
    while (true) {
        std::cout << prompt;
        if (std::cin >> value) {
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            return value;
        }
        std::cin.clear();                                                   // reset the flags
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // bin the bad input
        std::cout << "That is not a number. Try again.\n";
    }
}

if (std::cin >> value) works because the stream converts to bool: true if the read succeeded. clear() resets the error flags and ignore() throws away the offending characters. Without both, you get an infinite loop of failures — a classic beginner mystery.


Real World Example: A Tip Splitter

#include <iostream>
#include <limits>
#include <string>

int main() {
    std::string restaurant;
    double bill{};
    int people{};

    std::cout << "Restaurant name: ";
    std::getline(std::cin, restaurant);        // getline FIRST -- nothing to clean up yet

    std::cout << "Total bill: ";
    while (!(std::cin >> bill) || bill <= 0) {
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        std::cout << "Enter a positive amount: ";
    }

    std::cout << "Number of people: ";
    while (!(std::cin >> people) || people < 1) {
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        std::cout << "Enter at least 1: ";
    }

    const double withTip = bill * 1.15;
    const double each = withTip / people;

    std::cout << "\n" << restaurant << "\n";
    std::cout << "Bill with 15% tip: " << withTip << "\n";
    std::cout << "Each person pays:  " << each << "\n";
    return 0;
}

Notice the ordering: the getline happens before any >>, so there is no stray newline to trip over. Both numeric reads are wrapped in validation loops, so the program cannot proceed with garbage. The two derived values are const because nothing should change them after the arithmetic.


Common Mistakes

  • Mixing >> and getline without ignore. The single most common C++ input bug. The name prompt appears to be skipped.
  • Not checking whether the read succeeded. std::cin >> age on non-numeric input leaves age at its previous value and poisons the stream.
  • Calling clear() but not ignore(). You reset the flags but the bad characters are still queued, so the next read fails on the same text — forever.
  • Reading into an uninitialised variable and hoping. int age; followed by a failed read leaves age holding garbage. Write int age{};.
  • Using std::cin >> name for full names. You silently keep only the first word.
  • Forgetting the includes. std::getline needs <string>; std::numeric_limits needs <limits>.

Best Practices

  1. Always initialise: int n{}; not int n;.
  2. Wrap input in a helper like readInt and call it everywhere, rather than repeating the clear/ignore dance.
  3. Prompt without a newline (std::cout << "Age: ";) so the cursor stays on the same line as the question.
  4. Prefer getline plus your own parsing for anything user-facing; it never leaves half a line behind.
  5. Treat all input as hostile. Assume the user will type letters into a number field, because eventually they will.

Practice Exercises

  1. Greeter: Ask for a full name with getline and an age with >>, then print "Hello NAME, next year you will be X". Get the ordering right so neither prompt is skipped.
  2. Bulletproof reader: Write int readIntInRange(const std::string& prompt, int lo, int hi) that loops until the user supplies a number inside the range, rejecting both non-numbers and out-of-range values.
  3. Sum until stop: Read numbers with while (std::cin >> value) and print the running total, count and average when input ends. Test it by piping a file of numbers into your program.