How to get std::string from command line arguments in win32 application?
So now I have a
int main (int argc, char *argv[]){}
how to make it string based? will int main (int开发者_StackOverflow argc, std::string *argv[])
be enough?
You can't change main's signature, so this is your best bet:
#include <string>
#include <vector>
int main(int argc, char* argv[])
{
std::vector<std::string> params(argv, argv+argc);
// ...
return 0;
}
If you want to create a string out of the input parameters passed, you can also add character pointers to create a string yourself
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
string passedValue;
for(int i = 1; i < argc; i++)
passedValue += argv[i];
// ...
return 0;
}
You can't do it that way, as the main function is declared explicitly as it is as an entry point. Note that the CRT knows nothing about STL so would barf anyway. Try:
#include <string>
#include <vector>
int main(int argc, char* argv[])
{
std::vector<std::string> args;
for(int i(0); i < argc; ++i)
args.push_back(argv[i]);
// ...
return(0);
}; // eo main
That would be non-standard because the Standard in 3.6.1
says
An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation-defined. All implementations shall allow both of the following definitions of main:
int main() { /* ... */ }
and
int main(int argc, char* argv[]) { /* ... */ }
No. That is not allowed. If present, it is mandated to be char *argv[].
BTW, in C++ main should always be declared to return 'int'
main receives char*. you will have to put the argv array into std::strings yourself.
精彩评论