Create your own
Lesson illustration

Reading User Input with std::cin

Good to see you again. Previously, you created variables with types such as int, double, and char, gave them initial values, displayed them with std::cout, and updated them. Until now, those values were written directly into the program. This lesson makes your programs interactive: the person running the program will provide values at the console.

You will learn to prompt for a value, read it with std::cin, store it in a correctly typed variable, and display it back. By the end, you will have turned the study-session tracker into a small console check-in program.


Input: letting the user provide the value

C++ provides std::cin for standard input, usually the keyboard in a console program. It is available through the same header as std::cout:

#include <iostream>

The two stream objects have opposite roles:

Code patternPurpose
std::cout << value;Sends a value to the console.
std::cin >> variable;Reads typed input into a variable.

The symbols help show the direction of movement:

std::cout << studyMinutes;

This displays the value stored in studyMinutes.

std::cin >> studyMinutes;

This waits for the user to type a value, then stores that value in studyMinutes.

The >> operator is called the extraction operator because it extracts characters from the input stream and converts them into the type of the variable on its right.

Watch this concise demonstration before writing your own program.

User Input With cin Basics | C++ Tutorial

Watch “User Input With cin Basics” from Portfolio Courses for a visual walkthrough of one value, multiple values, and the role of whitespace in console input.

Watch one input to see the basic prompt, variable, and std::cin statement together. Then watch multiple inputs for a rectangle example that reads two double values and shows that spaces, tabs, and newlines can separate inputs.

A basic interaction has three steps:

  1. Create an appropriately typed variable.
  2. Tell the user clearly what to enter.
  3. Read their response with std::cin.

For example:

int age {};

std::cout << "Enter your age: ";
std::cin >> age;

std::cout << "You entered " << age << '\n';

If the person types 25 and presses Enter, the result looks like this:

Enter your age: 25
You entered 25

Notice that the cursor stays on the same line as the prompt. That is intentional: the input appears naturally after the colon. You do not need to add '\n' to a prompt before reading input, because pressing Enter moves the console to the next line.

Although std::cin will overwrite the variable with a user-provided value, continue the habit from the previous lesson: initialize local variables.

int age {};

The empty braces give age the initial value 0. In a later lesson, you will learn how to check and recover from bad input; initialization helps ensure that a variable has a known state from the moment it is created.

For a second explanation and a useful preview of how several inputs can be read, use this short section from LearnCpp.

1.5 — Introduction to iostream: cout, cin, and endl – Learn C++

Read the std::cin section from LearnCpp. It reinforces the prompt-read-display pattern and introduces extracting two values with one std::cin statement.

In the section titled “std::cin,” first examine the one-number program beginning with the prompt “Enter a number:”. Then read the walkthrough that explains why the program pauses and when the typed value becomes available. Continue to the following two-number example, focusing on the line that contains two >> operators and on the note that spaces, tabs, and newlines can separate entered values.


The variable type determines the expected input

std::cin does not merely store whatever characters were typed. It tries to interpret those characters according to the variable’s type.

int completedLessons {};
double breakMinutes {};
char sessionCode {};

Each variable expects a different kind of input:

Variable typeAppropriate user inputExample
intA whole number30, 0, -4
doubleA number that may contain a decimal part5.5, 18.25
charOne non-space characterA, q, 7

The corresponding input statements look nearly identical:

std::cin >> completedLessons;
std::cin >> breakMinutes;
std::cin >> sessionCode;

What changes is the variable after >>.

For example, this program reads a decimal measurement:

double temperatureCelsius {};

std::cout << "Enter the temperature in Celsius: ";
std::cin >> temperatureCelsius;

std::cout << "Recorded temperature: "
          << temperatureCelsius
          << '\n';

If the user enters 21.5, C++ converts the typed characters into a double and stores that value in temperatureCelsius.

A prompt should tell the user the meaning and expected form of the value. Compare these:

std::cout << "Enter value: ";
std::cout << "Enter break length in minutes, such as 5.5: ";

The second prompt makes it much easier for someone to give the program useful input.


Build: an interactive study-session check-in

Open the console project you used in the previous lessons. Replace the contents of your .cpp file with this program:

#include <iostream>

int main()
{
    int studyMinutes {};
    double breakMinutes {};
    char sessionCode {};

    std::cout << "Enter your study target in whole minutes: ";
    std::cin >> studyMinutes;

    std::cout << "Enter your planned break in minutes: ";
    std::cin >> breakMinutes;

    std::cout << "Enter a one-character session code: ";
    std::cin >> sessionCode;

    std::cout << "\n--- Study Session Plan ---\n";
    std::cout << "Study target: " << studyMinutes << " minutes\n";
    std::cout << "Planned break: " << breakMinutes << " minutes\n";
    std::cout << "Session code: " << sessionCode << '\n';

    return 0;
}

Save the file with Ctrl+S, then run without debugging with Ctrl+F5.

Try entering:

45
7.5
B

Your console should resemble this:

Enter your study target in whole minutes: 45
Enter your planned break in minutes: 7.5
Enter a one-character session code: B

--- Study Session Plan ---
Study target: 45 minutes
Planned break: 7.5 minutes
Session code: B

Trace the execution carefully:

  1. The program creates three initialized variables.
  2. The first prompt is displayed.
  3. At std::cin >> studyMinutes;, the program waits for input. After you type a whole number and press Enter, it stores that number.
  4. The same pattern reads a decimal double and then one char.
  5. Finally, std::cout displays the values that the user supplied.

The program’s source code stays the same on every run, but its output can change because the input changes. That is the essential difference between a fixed demonstration and an interactive program.


Reading several values and understanding whitespace

The extraction operator can be repeated in one statement:

std::cin >> studyMinutes >> breakMinutes >> sessionCode;

This reads three values in order. The user may put them on one line:

45 7.5 B

Or on separate lines:

45
7.5
B

Both forms work because std::cin treats spaces, tabs, and newlines as whitespace. Before each extraction, it skips leading whitespace and looks for the next value.

You could simplify the check-in program’s input section to this:

std::cout << "Enter study minutes, break minutes, and a session code: ";
std::cin >> studyMinutes >> breakMinutes >> sessionCode;

This is compact and useful when the inputs naturally belong together. However, separate prompts are often friendlier for a beginner-facing program because they explain each value one at a time.

There is one important consequence of this behavior: if the user types several values at once, C++ may already have later values waiting in its input buffer. A later std::cin statement can use them immediately rather than pausing again. This is normal, not a bug.

For instance, consider:

int firstNumber {};
int secondNumber {};

std::cout << "Enter two whole numbers: ";
std::cin >> firstNumber;
std::cin >> secondNumber;

Typing 4 9 after the first prompt supplies both values. The first extraction stores 4; the second extraction then uses the waiting 9.


What can go wrong?

For now, enter values that match each prompt. If a variable is an int, enter a whole number. If it is a double, enter a numeric decimal value when needed. If it is a char, enter one character.

These are common mistakes:

SituationExampleWhat to do instead
Text entered where an integer is expectedType many for int studyMinutesEnter a whole number, such as 45.
Decimal entered where a whole number is intendedType 45.5 for an intUse an int input such as 45, or redesign the value as a double if fractions make sense.
Using std::cout to try to read inputstd::cout << studyMinutes;Use std::cin >> studyMinutes;.
Forgetting the promptOnly writing std::cin >> studyMinutes;Explain what the user should type before reading it.
Writing quotes around a variablestd::cin >> "studyMinutes";Use the variable name without quotes: std::cin >> studyMinutes;.
Entering a whole word for a charType Blue for char sessionCodeUse one character, such as B.

When input does not match the expected type, std::cin can enter a failure state. Subsequent input operations may then fail too until the program deliberately repairs the input stream. Do not try to solve that problem yet; the course will return to it in the loops and validation module, where you will have the tools to repeatedly request valid input.

For today, observe the central rule:

The type of the variable is part of the conversation between your program and its user.

A prompt asks for a particular kind of value, and the variable provides the storage designed for that value.


Small, purposeful edits

Use the study-session program for a few brief experiments:

  • Change the first prompt and variable to collect a number of completed lessons instead of study minutes.
  • Replace sessionCode with a char named moodCode, then try inputs such as E or T.
  • Change the input section to the single chained std::cin statement and enter all three values on one line.
  • Enter extra spaces before a value and observe that std::cin still reads it correctly.
  • Predict what will happen if you enter letters when the program requests whole study minutes, then test it once. Restart the program before continuing with normal input.

Keep the program simple: it collects and reports data. In the next lesson, you will use arithmetic to transform that data into a more useful result.


Key takeaways

  • std::cin reads keyboard input in a console program; it is available through #include <iostream>.
  • Use std::cin >> variable; to store a typed value in an existing variable.
  • Prompt before reading so the user knows what type and meaning of value to provide.
  • The destination variable’s type determines how C++ interprets the input: int for whole numbers, double for decimal values, and char for one character.
  • Multiple extractions can be chained, such as std::cin >> x >> y;.
  • Spaces, tabs, and newlines separate input values, so several values can be entered on one line or on separate lines.
  • For now, assume valid input. Later, you will learn to detect and recover from invalid entries.

Next, you will combine std::cin, variables, arithmetic, and formatted output to build a temperature-conversion program.

Can't find a good explanation? Sign up and we'll make it for you

Sign up