comparison between string literal

前端 未结 4 904
后悔当初
后悔当初 2020-11-30 12:25

This very simple code:

#include 

using namespace std;

void exec(char* option)
{
    cout << \"option is \" << option << e         


        
4条回答
  •  一向
    一向 (楼主)
    2020-11-30 12:41

    For C++ I would use the std::string solution:

    #include  
    #include 
    
    using namespace std; 
    
    void exec(string option) 
    { 
        cout << "option is " << option << endl; 
        if (option == "foo") 
            cout << "option foo"; 
        else if (option == "bar") 
            cout << "option bar"; 
        else 
            cout << "???"; 
        cout << endl; 
    } 
    
    int main() 
    { 
        string opt = "foo"; 
        exec(opt);
    
        exec("bar");
    
        char array[] = "other";
        exec(array);
        return 0; 
    } 
    

    std::string knows how to create itself out of char[], char*, etc, so you can still call the function in these ways, too.

提交回复
热议问题