Menu
Coddy logo textTech

cin Statement

Part of the Fundamentals section of Coddy's C++ journey — lesson 34 of 74.

As of now we stored values that we thought about in variables. Programs usually don't work this way. We receive values from an outer source, a user for example.

In C++, getting input from a user is done using the cin statement. This statement provides methods to read different types of input, such as integers, floating-point numbers, and strings.

To use the cin statement, you first need to declare a variable to store the input value. Then, you can use the extraction operator >> to read the input from the standard input stream std::cin and store it in the variable. Here's how you do it:

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

The extraction operator >> will automatically convert the input to the appropriate data type based on the variable you're storing it in. For example:

// For integers:
std::cin >> intVariable;

// For doubles:
std::cin >> doubleVariable;

// For strings:
std::cin >> stringVariable;

For boolean values in C++, cin can handle input in two ways:

1. By default, cin reads only 0 (stored as false) or 1 (stored as true) into a bool. Any other input, such as 5, causes extraction to fail and sets the stream's failbit, storing false since C++11.

2. To read the words true or false directly, you must first set std::cin >> std::boolalpha; otherwise those words fail to extract.

challenge icon

Challenge

Beginner

Write a program that gets input from the user (their name), and then outputs Hello, followed by the user's inputted name.

For example, if the user inputs Bob, the expected output is Hello, Bob.

You will need to:

  1. Create an string variable to store the name.
  2. Prompt the user to enter their name.
  3. Read the user's name using the appropriate cin method.
  4. Print Hello, and the stored variable in the end.

Try it yourself

#include <iostream>
#include <string>

int main() {
    
    // Prompt the user to enter their name
    std::cout << "Enter your name: ";
    
    // Read the user's name
    std::string name;
    
    // Print the greeting message
    
    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals