← C++ from Scratch Lesson 16 of 62 · 10 XP

switch

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

switch picks a branch by the exact value of an integer, a character or an enum:

switch (cmd) {
case 'w': y--; break;
case 's': y++; break;
case 'a': x--; break;
case 'd': x++; break;
default:  std::cout << "?\n"; break;
}
  • after case comes a constant; strings (std::string) aren't allowed in a switch;
  • break is a must: without it, execution "falls through" into the next case (sometimes on purpose — several values for one branch: case 'a': case 'A': …);
  • default runs if none of the values matched.

Task. Read a string of commands made of the characters w a s d (no spaces). The hero stands at (0, 0); w — y+1, s — y−1, d — x+1, a — x−1, and any other character is skipped. Print the final coordinates x y.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.