0

Code below return error: switch quantity not an integer. What's wrong?

string s = "20";
  
  switch (s){
    
    case "18":
      cout << "18" << "\n";
      break;
      
    case "20":
      cout << "20" << "\n";
      break;
    
  }
Nazar Vozniy
  • 51
  • 1
  • 7

1 Answers1

2

The cases have to be integral types and compile time evaluable constant expressions.

Rather than fighting the language, use an if else block. Or if you can use integral types, then do so:

int n = 20;  
switch (n){    
case 18:
    std::cout << n << "\n";
    break;      
case 20:
    std::cout << n << "\n";
    break;    
}

noting that the ostream << operator has an overload for int.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483