c++if-statement

Cleaner if statement sequence in C++


I am a bit of a newbie so please go easy on me. I wanted to know if there was a way to shorten these if statement chains like the one shown below in C++.

int offset;
    
string S;
cin >> S;

if(S == "mon")
{ offset = 0; }
else if(S == "tues")
{ offset = 1; }
else if(S == "wed")
{ offset = 2; }
else if(S == "thurs")
{ offset = 3; }
else if(S == "fri")
{ offset = 4; }
else if(S == "sat")
{ offset = 5; }
else if(S == "sun")
{ offset = 6; }

Solution

  • I would suggest using std::map.

    std::map<std::string, int> m { 
      {"mon", 0}, {"tues", 1}, {"wed", 2}, {"thurs", 3},
      {"fri", 4}, {"sat", 5}, {"sun", 6}
    };
    
    std::string s;
    std::cin >> s;
    
    int offset = m.at(s);
    

    If s is not a valid key, the std::out_of_range exception will be thrown. You might handle that by putting a try block in a loop and gathering input until you get a valid key, as shown below.

    #include <iostream>
    #include <stdexcept>
    #include <map>
    
    int main() {
      std::map<std::string, int> m { 
        {"mon", 0}, {"tues", 1}, {"wed", 2}, {"thurs", 3},
        {"fri", 4}, {"sat", 5}, {"sun", 6}
      };
    
      std::string s;
    
      while (true) {
        try {
          std::cin >> s;
          int offset = m.at(s);
          std::cout << offset << std::endl;
          break;
        }
        catch (std::out_of_range e) {
          std::cerr << "Invalid input: " << s << std::endl;      
        }
      }
    
      return 0;
    }
    

    You could also refactor your original code to use ? : (the actual name is somewhat debatable). Of course, this requires us to provide an else case, so let's go with -1.

    int offset =
      s == "mon"   ? 0 :
      s == "tues"  ? 1 :
      s == "wed"   ? 2 :
      s == "thurs" ? 3 :
      s == "fri"   ? 4 :
      s == "sat"   ? 5 :
      s == "sun"   ? 6 : -1;