User Input

C++ · Lesson 6 of 32 6 min read Updated

Most useful programs need information from the person using them: a name, a quantity, a choice from a menu. In C++ you read keyboard input with std::cin (pronounced "see-in", short for character input) from the <iostream> header.

In this lesson you will read numbers and words, read whole lines with spaces, avoid the most famous input bug in C++, and keep asking until the user types something valid.

Because these programs wait for typing, the output blocks below show a sample run: the text after each prompt is what the user typed before pressing Enter.

Reading numbers and words with std::cin

The >> operator reads the next value from the keyboard and stores it in a variable. It converts the text automatically to the variable's type.

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

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

    std::print("Enter your first name: ");
    std::cin >> name;
    std::print("Enter your age: ");
    std::cin >> age;

    std::println("Hi {}, in 5 years you will be {}.", name, age + 5);
}
Output
Enter your first name: Kabir
Enter your age: 19
Hi Kabir, in 5 years you will be 24.

std::print writes the prompt without a newline, so the user types on the same line. Before std::cin waits for input, it makes sure all earlier output has appeared on the screen, so the prompt is always visible.

You can read several values in one statement. >> skips spaces, tabs and newlines between values, so the user can type them on one line or on separate lines:

C++
#include <iostream>
#include <print>

int main() {
    int length = 0;
    int width = 0;
    std::print("Enter room length and width in feet: ");
    std::cin >> length >> width;
    std::println("Floor area: {} sq ft", length * width);
}
Output
Enter room length and width in feet: 12 8
Floor area: 96 sq ft

Reading a whole line with std::getline

std::cin >> name stops at the first space. If Kabir types Kabir Singh, only Kabir goes into name, and Singh stays waiting in the input for the next read. To read a full line, spaces included, use std::getline:

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

int main() {
    std::string full_name;
    std::print("Enter your full name: ");
    std::getline(std::cin, full_name);
    std::println("Welcome, {}! Your name has {} characters.", full_name, full_name.size());
}
Output
Enter your full name: Kabir Singh
Welcome, Kabir Singh! Your name has 11 characters.

std::getline reads everything up to the Enter key and throws the newline character away.

The leftover newline problem

Here is the bug almost every C++ learner meets. When you type 42 and press Enter, the input contains 42 followed by a newline character. std::cin >> roll takes the 42 but leaves the newline behind. A following std::getline sees that newline straight away and returns an empty line without waiting for you.

The fix is std::ws, which skips any leading whitespace (spaces and newlines) before getline starts reading:

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

int main() {
    int roll = 0;
    std::string city;

    std::print("Roll number: ");
    std::cin >> roll;
    std::print("City: ");
    std::getline(std::cin >> std::ws, city);   // skip the leftover newline

    std::println("Roll {} lives in {}.", roll, city);
}
Output
Roll number: 42
City: Navi Mumbai
Roll 42 lives in Navi Mumbai.

Without >> std::ws, the program would print Roll 42 lives in . without ever letting you type the city.

Validating input

What happens if the user types ninety when you ask for a number? The read fails, the variable is set to 0, and std::cin enters a fail state: every later read is ignored until you reset it. A robust program checks each read and asks again. This example uses a loop and if statements, which you will study properly in the next two lessons.

C++
#include <iostream>
#include <limits>
#include <print>

int main() {
    int marks = 0;
    while (true) {
        std::print("Enter marks (0-100): ");
        if (std::cin >> marks && marks >= 0 && marks <= 100) {
            break;                                   // valid: leave the loop
        }
        if (std::cin.eof()) {                        // input closed, give up
            return 1;
        }
        std::println("Please type a whole number from 0 to 100.");
        std::cin.clear();                            // leave the fail state
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
    std::println("Saved marks: {}", marks);
}
Output
Enter marks (0-100): ninety
Please type a whole number from 0 to 100.
Enter marks (0-100): 150
Please type a whole number from 0 to 100.
Enter marks (0-100): 90
Saved marks: 90

std::cin >> marks can be used as a condition: it is true when the read worked. clear() resets the fail state, and ignore(...) throws away the rest of the bad line, up to and including the newline, so the next attempt starts fresh. The eof() check stops the loop if the input ends, for example when the user presses Ctrl+Z on Windows or Ctrl+D on Linux and macOS.

Common mistakes

  • Mixing >> and getline without std::ws. The leftover newline makes getline return an empty string.
  • Reading a name with >>. Names, addresses and sentences contain spaces; use getline.
  • Not checking the read. If std::cin >> qty fails, qty becomes 0 and later reads silently do nothing.
  • Forgetting clear() before ignore(). While the stream is in the fail state, ignore does nothing either.

Key points

  • std::cin >> variable reads one value and converts it to the variable's type; it stops at whitespace.
  • std::getline(std::cin, text) reads a whole line, spaces included.
  • After >>, use std::getline(std::cin >> std::ws, text) to skip the leftover newline.
  • A failed read puts std::cin in a fail state; check reads, then clear() and ignore() before trying again.
  • Show prompts with std::print so the user types on the same line.

Exercise

Write a program for a sweet shop in Jaipur. Ask for the customer's full name (it may contain spaces), then the number of boxes of ghevar (a whole number from 1 to 20, asked again until valid), then print a bill line such as Bill for Isha Sharma: 3 boxes x Rs. 450 = Rs. 1350.

Show solution
C++
#include <iostream>
#include <limits>
#include <print>
#include <string>

int main() {
    constexpr int box_price = 450;
    std::string name;
    int boxes = 0;

    std::print("Customer name: ");
    std::getline(std::cin, name);

    while (true) {
        std::print("Boxes (1-20): ");
        if (std::cin >> boxes && boxes >= 1 && boxes <= 20) {
            break;
        }
        if (std::cin.eof()) {
            return 1;
        }
        std::println("Please enter a number from 1 to 20.");
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }

    std::println("Bill for {}: {} boxes x Rs. {} = Rs. {}", name, boxes, box_price, boxes * box_price);
}
Output
Customer name: Isha Sharma
Boxes (1-20): 0
Please enter a number from 1 to 20.
Boxes (1-20): 3
Bill for Isha Sharma: 3 boxes x Rs. 450 = Rs. 1350

The name is read first with getline, so there is no leftover newline problem. The loop accepts only a successful read in the allowed range.

Quick Quiz

1. The user types Priya Das for std::cin >> name;. What is stored in name?

2. Why does getline sometimes return an empty string right after std::cin >> number?

3. What must you do after a failed read before reading again?

4. Which header declares std::cin?

Learn C++ with a mentor

Free lessons get you started. Our Java, C & C++ Programming training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call