Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

C++ User Input (cin, getline)

std::cin reads what the user types. The input operator >> reads a value into a variable, and the variable's type decides what is read. In the editor, type your input in the terminal when the program waits, then press Enter.

Reading numbers and words

#include <iostream>
#include <string>

int main() {
    std::string name;
    int age;
    std::cout << "What is your name? ";
    std::cin >> name;
    std::cout << "How old are you? ";
    std::cin >> age;
    std::cout << "Hello " << name << "! Next year you will be " << age + 1 << ".\n";
    return 0;
}
You type
Asha
12
Output
What is your name? How old are you? Hello Asha! Next year you will be 13.

Reading into a string stops at the first space, so cin >> name reads one word. Several values can be read in one statement: std::cin >> a >> b;.

Checking the input

If the user types letters where a number is expected, cin fails: the variable becomes 0 and further reads do nothing. Test the read itself: if (std::cin >> n) is true only when it worked.

#include <iostream>

int main() {
    int n;
    std::cout << "A whole number: ";
    if (!(std::cin >> n)) {
        std::cout << "That is not a whole number.\n";
        return 1;
    }
    std::cout << "You typed " << n << ".\n";
    return 0;
}
You type
abc
Output
A whole number: That is not a whole number.

To try again after a failure, call std::cin.clear() to reset the error and std::cin.ignore(1000, '\n') to throw away the bad line.

Whole lines with getline

std::getline(std::cin, text) reads a whole line, spaces included.

#include <iostream>
#include <string>

int main() {
    int age;
    std::string city;
    std::cout << "Age? ";
    std::cin >> age;
    std::cin.ignore();                // skip the Enter left after the number
    std::cout << "City? ";
    std::getline(std::cin, city);
    std::cout << age << ", from " << city << "\n";
    return 0;
}
You type
12
New Delhi
Output
Age? City? 12, from New Delhi

The ignore() matters: after cin >> age, the Enter key is still waiting, and getline would read that empty rest of the line. Skip it first whenever you switch from >> to getline.

Reading until the end

while (std::cin >> n) keeps reading numbers until the input ends (Ctrl+D in the terminal) or something that is not a number is typed. It is the usual way to read a list of unknown length.

Practice exercises

  1. Read the length and width of a rectangle and print its area and perimeter.
  2. Read a full name with getline and print it with its number of characters.
  3. Ask for a number again and again until the user types a valid one, using clear and ignore.