This is part three of my tutorial series on how to program in C++. In this tutorial, weâ€™re going to build on what we saw in the last tutorial. We revise the very basics of cout, we introduce cin, and using our knowledge of cout and cin, we create a very basic console calculator.
NOTE: If you haven’t read the previous parts of this tutorial series, please do so right here.
In both previous tutorials, we’ve taken a look at cout, which is used for printing text to the console. Now, we’re going to take a look at its big brother, cin. As you might expect, cin is used for user input. Now, let’s take a look at some example code. Let’s revise the basics of cout:
cout << "Hello World" << endl;
As you already know, this is a typical use of cout. A string (“Hello World”) is printed to the console, and we start a new line. If you don’t understand this, you can revise all the details at the previous tutorial, right here. Now, here is a use of cin:
cin >> number;
Now, what does this code do? It’s pretty simple, we create an integer variable called number, and then we use cin to ask for user input. On this moment, the user has to type an integer value, and hit enter. The entered value will then be stored in the variable number.
NOTE: Where we use the insertion operator (<<) in cout, we now use the extraction operator (>>).
Now, with our knowledge, we can create a simple calculator. We’re going to ask the user for two integer variables, and then we’re going to return the sum of those variables. Here is the main function for this program:
cout << "Please enter two integer values." << endl;
cin >> first;
cin >> second;
int sum = first + second;
cout << "The sum of these variables is " << sum << endl;
So, as you can see, it’s pretty simple. first, we tell the user to enter two integer values, by printing the request to the console. Then we create an integer variable called “first” (This doesn’t have to be “first” ,you can call this variable whatever you want, like “bacon”, as long as you remember that this variable is then called “bacon”, and not “first” throughout the code.), and we ask for user input. At this point, the user types an integer value, like 3, or 568, and hits enter. This value is then stored in “first” (Or “bacon”.). Then we do the same thing with a second value, we create the variable, and we store whatever the user types. Then, we create a new variable, called “sum”. Here, we store the sum of “first” and “second” (That’s quite obvious.). Then, we print that value back to the console using cout.
NOTE: In the last line, we print a string, as well as the integer variable “sum”. To do this, we use << twice. This code is equivalent to:
cout << “The sum of these variables is “;
cout << “sum”;
In the next tutorial, we’re going to take a look at basic variable conversion, and some more awesome stuff.