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
.
main
argument must be char** argv
or char* argv[]
.
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 typeint
, but otherwise its type is implementation-defined. An implementation shall allow both(2.1). a function of
()
returningint
and(2.2). a function of
(int, pointer to pointer to char)
returningint
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
constructor, here using pointers to the beginning and to one past the end the array of strings argv
as constructor arguments: 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.