LearnFrenzy
Sign in Take a free test

std::string · Find the Error · Question 3

Error: switch on a std::string Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

main.cpp
#include <iostream>
#include <string>

int main() {
    std::string cmd = "start";
    switch (cmd) {
    case "start": std::cout << "starting\n"; break;
    case "stop":  std::cout << "stopping\n"; break;
    }
    return 0;
}
  • A The cases need braces
  • B switch works only with integral and enum values; use if / else if or a map from string to action Correct
  • C break is not allowed
  • D cmd must be const
Correct Answer: Option B

Case labels must be integer constant expressions. A std::map<std::string, std::function<void()>> is a clean replacement for many commands.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links