Modern C++: The Good Parts/Number crunching
The machine in front of you is really just a very fancy calculator, so let's make it calculate.
Code
[edit | edit source]#include <iostream>
#include <string>
int main()
{
std::string input;
int a, b;
std::cout << "Enter two integers to multiply.\n";
// Take input.
std::cin >> input;
// Parse it as an int.
a = std::stoi(input);
// Take input.
std::cin >> input;
// Parse it as an int.
b = std::stoi(input);
std::cout << a << " * " << b << " = " << a * b << "\n";
}
Explanation
[edit | edit source]So first we have a std::string
variable named "input" and two int
variables named "a" and "b". An int
is an integer or whole number, so it can't have a decimal point.
Important: The = (equals sign) does not mean equality. In C++ it's the assignment operator; it puts the value on the right into the variable on the left, overwriting any previous value of that variable.
std::stoi
is a function, and the name stands for string to int. It takes a string (in this case, the value of input
) and converts it to an integer. If this isn't possible, or you enter a very large number, the program will crash and you'll probably see something about an "unhandled exception". How to prevent this issue will be addressed a few chapters later.
You can read about std::stoi
at cplusplus.com or cppreference.com. It has some friends, too.
The multiplication operator in C++ is * (asterisk). Division is / (forward slash).
Try entering 3.14 as one of the integers. Oops! std::stoi
finds the valid integer 3 and ignores the invalid input after it. You'll get the same result for 3sdjgh. The next few chapters should allow you to write a better integer parser.
Exercises
[edit | edit source]- Modify the above program so it accepts decimal points (floating-point numbers or
float
values). Hint: Check the links on this page.
Vocabulary
[edit | edit source]- int
- an integer or "whole number". Cannot represent fractions.
- assignment operator
- puts the value on the right into the variable on the left, overwriting any previous value of that variable. Syntax:
=
- function
- a named piece of code. More on these later.
- float
- a floating-point number or "decimal number". (That last one is a little confusing.) Can represent some fractions.