Search code examples
c++printingenumeration

Print enum text instead of value C++


In Form.h I have:

enum Direction {
   NORTH = 0,
   SOUTH = 1,
   EAST = 2,
   WEST = 3,
};

In Play.cpp I have a method that prints the movement like "PlayerA moved to NORTH"

void Play::printMove(Direction dir) {
   std::cout << this->getName() << " moved to " << dir << std::endl;
} 

Because this printed 0, 1, 2 or 3 I tried:

void Play::printMove(Direction dir) {
   std::string moveStr;
   switch (dir) {
      case NORTH: moveStr = "NORTH";
      case SOUTH: moveStr = "SOUTH";
      case EAST: moveStr = "EAST";
      case WEST: moveStr = "WEST";
   }
   std::cout << this->getName() << " moved to " << moveStr << std::endl;
}

But this didn't work either. Why? What can I try?


Solution

  • You need the break keyword or else printMove() will always result in "WEST". As soon as the computer finds a case that matches, it reads the code that follows all the way through the switch statement. The break keyword tells the computer to stop reading and continue the program after the end bracket of the switch.

    void Play::printMove(Direction dir) {
        std::string moveStr;
        switch (dir) {
            case NORTH: 
                moveStr = "NORTH";
                break;
            case SOUTH:
                moveStr = "SOUTH";
                break;
            case EAST:
                moveStr = "EAST";
                break;
            case WEST: 
                moveStr = "WEST";
                break;
        }
        std::cout << this->getName() << " moved to " << moveStr << std::endl;
    }