In practice, the string series in c ++ -- use string in the switch statement (c ++ does C #, and break in the switch is still very powerful)

Source: Internet
Author: User
Tags switch case

In practice, the string series in c ++ -- use string in the switch statement (c ++ does C #, and break in the switch is still very powerful)

How many times have you written this as a C ++ programmer out of habit or helplessness:

if (!strcmp(pszValue, "Value X"))    DoThis();else if (!strcmp(pszValue, "Value Y"))    DoThat();else if (!strcmp(pszValue, "Value Z"))    DoSomethingElse();else    DontKnowWhatToDo();

You have asked for thousands of times how nice it would be to use a switch at this time?

switch(strValue){case "Value X":    DoThis();    break;case "Value Y":    DoThat();    break;case "Value Z";    DoSomethingElse();    break;default:    DontKnowWhatToDo();    break;

The above code is legal in C Sharp, but as a C ++ programmer, you can only be helpless and helpless.

Here is the desire to use enum and std: map!

#include#include 
   
    #include 
    
     // Value-Defintions of the different String valuesstatic enum StringValue { evNotDefined,                           evStringValue1,                           evStringValue2,                           evStringValue3,                           evEnd };// Map to associate the strings with the enum valuesstatic std::map
     
       s_mapStringValues;// User inputstatic char szInput[_MAX_PATH];// Intializationstatic void Initialize();int main(int argc, char* argv[]){  // Init the string map  Initialize();  // Loop until the user stops the program  while(1)  {    // Get the user's input    cout << "Please enter a string (end to terminate): ";    cout.flush();    cin.getline(szInput, _MAX_PATH);    // Switch on the value    switch(s_mapStringValues[szInput])    {      case evStringValue1:        cout << "Detected the first valid string." << endl;        break;      case evStringValue2:        cout << "Detected the second valid string." << endl;        break;      case evStringValue3:        cout << "Detected the third valid string." << endl;        break;      case evEnd:        cout << "Detected program end command. "             << "Programm will be stopped." << endl;        return(0);      default:        cout << "'" << szInput   << "' is an invalid string. s_mapStringValues now contains "             << s_mapStringValues.size()              << " entries." << endl;        break;    }  }  return 0;}void Initialize(){  s_mapStringValues["First Value"] = evStringValue1;  s_mapStringValues["Second Value"] = evStringValue2;  s_mapStringValues["Third Value"] = evStringValue3;  s_mapStringValues["end"] = evEnd;  cout << "s_mapStringValues contains "        << s_mapStringValues.size()        << " entries." << endl;}
     
    
   

Here is a particularly important technique, that is, why is the first enumeration set to evNotDefined?

First, we need to clarify the role of std: map: operator:
1. Set the value of a key
2. At this time, you must note that, if it does not exist, it will be inserted.

That is, for s_mapStringValues in the program, if szInput is new, it will be inserted.
And the value is 0 by default.
If the first item of enumeration is evStringValue1, any unknown string value will lead to a valid switch case. That's why we did this.

========================================================== ======================================
There is also a small question to discuss, that is, the return Statement in the switch statement is powerful or break is powerful:
Code:

Switch (s_mapStringValues [szInput]) {case evStringValue1: cout <"Detected the first valid string." <endl; return 0; // will break be executed? Break; case evStringValue2: cout <"Detected the second valid string. "<endl; break; case evStringValue3: cout <" Detected the third valid string. "<endl; break; case evEnd: cout <" Detected program end command. "<" Programm will be stopped. "<endl; return (0); default: cout <" '"<szInput <"' is an invalid string. s_mapStringValues now contains "<s_mapStringValues.size () <" entries. "<endl; break ;}

Test. On the surface, return won't break.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.