Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 argc, std::string *argv[]) be enough?

like image 243
Rella Avatar asked Nov 09 '10 14:11

Rella


4 Answers

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;
}
like image 137
luke Avatar answered Nov 14 '22 10:11

luke


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;
}
like image 23
JoshMachine Avatar answered Nov 14 '22 11:11

JoshMachine


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
like image 3
Moo-Juice Avatar answered Nov 14 '22 12:11

Moo-Juice


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[]) { /* ... */ }

like image 3
Prasoon Saurav Avatar answered Nov 14 '22 11:11

Prasoon Saurav