Learn
Variables
User Input

Like we mentioned in the introduction, another way to assign a value to a variable is through user input. A lot of times, we want the user of the program to enter information for the program.

We have cout for output, and there is something called cin that’s used for input!

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

The name cin refers to the standard input stream (pronounced “see-in”, for character input). The second operand of the >> operator (“get from”) specifies where that input goes.

To see how it works, we have to try it with a program.

Instructions

1.

Add the following code:

std::cin >> tip;

So that the user of the program can enter something with their keyboard and what they enter gets saved in the int variable named tip.

2.

Let’s output the following using chaining:

You paid [tip] dollars.

where the [tip] should be the value of the variable tip.

Make sure to add a new line to the end of the output.

3.

Compile and execute your program using the terminal.

Your terminal then should look something like:

$ g++ tip.cpp $ ./a.out Enter a tip amount:

Type a number in the terminal and press enter.

Folder Icon

Take this course for free

Already have an account?