Let’s take the simple example from before, and work on getting inputs from a user:
#include <iostream>
using namespace std;
int main() {
double radius;
double area;
radius = 20;
area = radius * radius * 3.14159;
cout << "The area of the circle is: " << area;
return 0;
}
In the example, we specifically set the radius, however we want to get that information from the user.
With Python, we had a single command, however in C++ getting an input will consist of two steps. First we need to prompt the user. Failing to do that will cause “blinking cursor syndrome” where the user sees just a blinking cursor and doesn’t know what to do with it.
The second step is actually causing the computer to listen for the input.
// commenting out the line so we can write actual code
// radius = 20
cout << "Please enter the radius of the circle: ";
cin >> radius;
Notice that the angle brackets are pointed in the opposite direction. This is because instead of sending information to the console, we’re taking it from the console and putting it into the variable.
Because we have defined the data type for the variable, C++ is smart enough to know what the data type is and do the conversion for us automatically, instead of like Python, where everything was a string and we had to convert it to a number.
The rest of the program stays the same, and should execute the same way you did with the last example.
Working with Console Inputs was originally found on Access 2 Learn