Introduction
In the previous tutorial we learned how to compile a program and write a message to the screen. In this tutorial we are going to learn how to read in data that they user types in and store that information.
Code
So, let’s jump right into an example. Here’s how to read in user input and repeat it back to the user:
#include <iostream>
using namespace std;
int main()
{
cout << “Enter your favorite number:” << endl;
int num = 0;
cin >> num;
cout << “Your favorite number is “ << num << endl;
return 0;
}
Now if you have read the first tutorial, most of this code should seem very familiar. There are a couple of new pieces, the first one being this line:
int num = 0;
This line declares a variable, which tells the computer that we want it to store some information for us. In this case, we want the computer to store an integer number. If we wanted the computer to store a fractional value, we would change int to be double (double precision floating point number). If we wanted the computer to store a letter we would use a char (character). Finally, if we wanted to store either true or false we would use a bool (boolean). This line also sets the value of the variable to zero.
The next line is also new:
cin >> num;
This tells the computer to read in a number from the command line and store it in the num variable. There’s some nice symmetry here: the command to write to the screen is cout (console output) and we provide direction symbols going from our message to the screen (<<), and the command to read from the screen is cin (console input) and we provide direction symbols going from the screen to the variable that we would like to store the input in (>>).
With the cout (or cin) command, you can specify one value or variable after another to write to (or read from) the screen. That’s why the following command works:
cout << “Your favorite number is “ << num << endl;
It writes out the message that we want and the immediately follows it with the value stored in the num variable. The endl tells the computer that it is the end of the line, so the next piece of text will start on the next line (much like hitting enter).
Summary
In this tutorial we discussed how to read in data from the user and store it in a variable. I encourage you to make changes to the program and read in fractional numbers (double) and letters (char) from the user. Experiment and see what happens!
The next step will be making decisions based on what the user types in. This will let us create our first game: guess what number I’m thinking of.
If you have any questions or comments about what was covered here, post them to the comments. I watch them closely and will respond and try to help you out.