Modern C++: The Good Parts/Switching things up

In the previous chapter, you received your first assignment: to write a simple calculator. At the time, if statements were your only way to make a decision; this chapter introduces the switch statement, which works similarly to the if statement but is more suited to problems like the calculator.

Code

edit

Here's a calculator built around a switch statement:

#include <iostream>
#include <string>

int main()
{
	std::string input;
	float a, b;
	char oper;
	float result;

	std::cout << "Enter two numbers and an operator (+ - * /).\n";
	
	// Take input.
	std::cin >> input;
	// Parse it as a float.
	a = std::stof(input);

	// Take input.
	std::cin >> input;
	// Parse it as a float.
	b = std::stof(input);

	// Take input.
	std::cin >> input;
	// Get the first character.
	oper = input[0];

	switch (oper)
	{
	case '+':
		result = a + b;
		break; // DON'T
	case '-':
		result = a - b;
		break; // FORGET
	case '*':
		result = a * b;
		break; // THESE
	case '/':
		result = a / b;
		break; // !!!
	}

	std::cout << a << " " << oper << " " << b << " = " << result << "\n";
}

Explanation

edit

std::stof is similar to std::stoi, except it converts to float.

input[0] is the first character in the string input. Anytime you see square brackets with a number (or variable) between them, the number is zero-based. This means that what people normally call the "first" character is at index 0, the "second" is at index 1, and so forth.

The switch statement has exactly the same effect as the if-else chain you wrote for your own calculator. Notice that every case label has a matching break statement; be careful that this is true of any switch statement you write, because otherwise you might get some very surprising behavior. Specifically, without a break statement, control will flow right past any labels, causing the logic under them to be executed in multiple cases.

Exercises

edit
  • Explore what happens when you divide one int by another, and how that differs from doing the same with two floats, and an int and a float. Discuss your findings with your instructor.

Vocabulary

edit
switch statement
uses its expression to select which case label to jump to.
Modern C++: The Good Parts
 ← Now it gets interesting. Switching things up Getting loopy →