Chris Gregory

Home Blog LinkedIn Github

C++ Tutorial 2 - Getting user input

12/19/2016

In this tutorial we will look at getting user input. We will start by getting the user's name. First we will ask the user to input their name. Then we will store their name into a variable and greet them.

#include <iostream>
#include <cstdio>
#include <string>

using namespace std;

int main() {
    // Ask the user to input their name.
    cout << "What is your name? ";

    // Declare a string variable.
    string name;
    // Store their input into the name variable.
    cin >> name;

    // Greet them.
    cout << "\n" << "Hello " << name << ".\n";

    // Visual Studio only for the following line.
    getchar();
    return 0;
}

To declare a variable, write Type variable_name;. On line 7, Type is string and variable_name is name.

To get input from the user, use cin and >> in conjunction with the variable to store the input in. To get a string from the user, their name, we wrote cin >> name.

We can use multiple << s to print out more data without having to rewrite the name of the stream, cout. The "\n"s tell the computer to print out a new line. This helps us read the output.

Now let us in addition get the age of the user. We need to declare an integer to store their age, read it from cin, and finally use it in some way. Let's print out a special message depending on if their age is less than 18.

#include <iostream>
#include <cstdio>
#include <string>

using namespace std;

int main() {
    // Ask the user to input their name.
    cout << "What is your name? ";

    // Declare a string variable.
    string name;
    // Store their input into the name variable.
    cin >> name;

    // Ask the user to input their name.
    cout << "\n" << "How old are you " << name << "? ";

    // Declare the age variable.
    int age;
    // Store their age into our variable.
    cin >> age;

    // If the user's age is less than 18
    if (age < 18) {
        cout << "\n" << "Go back to school!\n";
    } else {
        // Otherwise (age is at least 18)
        cout << "\n" << "I guess you will live another "
             << 100 - age << " years.\n";
    }

    // Visual Studio only for the following line.
    getchar();
    return 0;
}

We now see usage of another type of variable, the int. An int stores non-fractional numbers.

We also see usage of an if statement: a statement that branches our code based on the condition given. Here we test if the user is a child by comparing their age with 18. If they are a child, we tell them to go back to school. If they are an adult we predict how many years they have left to live, assuming they die at 100.