c++stringc++11argvargc

Can I use std::string* argv as main function argument?


Usually I see:

int main(int argc, char** argv)

But can I use:

int main(int argc, std::string* argv)

instead?

If it's not possible how can I convert char* to std::string?

PS: I am using C++11.


Solution

  • main argument must be char** argv or char* argv[].

    [basic.start.main]

    2. An implementation shall not predefine the main function. This function shall not be overloaded. Its type shall have C++ language linkage and it shall have a declared return type of type int, but otherwise its type is implementation-defined. An implementation shall allow both

    (2.1). a function of () returning int and

    (2.2). a function of (int, pointer to pointer to char) returning int


    What you can do is to convert the arguments in the code by using one of the following:

        if(argc > 1)
        { 
            std::string str = argv[1]; 
        }
    
        std::string str(argv[1]);
    
        std::string str{argv[1]};
    

    If you'd like to keep a collection of the arguments I would suggest keeping them in a variable size container std::vector using one of the following:

        std::vector<std::string> strs(&argv[1], &argv[argc]); //*
    
        std::vector<std::string> strs{&argv[1], &argv[argc]}; //*
    
        std::vector<std::string> strs;
    
        for(int i = 1; i < argc; i++) //*
            strs.push_back(argv[i]);   
        }
    

    *Not including argv[0] program name.