1.1.3 Input and Output

In your last example, you took a look at a basic output statement using the cout command. In this example, you are going to look at how to take user input.

There are two main ways that you can read in from the user: cin and getline

cin

cin is used to read one item at a time, such as one number or one word.

You input from the console to a variable using double angled brackets going in the opposite direction from the cout angled brackets, >>. For example, if you wanted to get an input from the user and store it in the name variable, the syntax would look like this:

cin >> name;

Prior to the input, you need to use the cout command to prompt the user.

You then create a variable and use the cin command to stream the input into the variable. (You will see more about variables in the next lesson.)

The variable needs to be created prior to streaming into it.

getline

getline is used to read an entire line in as a string You use a single command with two arguments. The first argument is where the input comes from and the second is where it goes. For example, if you want to read a line from the console and store it in the name variable, the syntax would look like this:

getline(cin, name);

Like the cin option, you still prompt the user and create a variable, however the input is assigned to the variable using the getline command. No assignment operator (=) is used.

Last updated