开发者

C++ command line strings like Java?

Is there a way to get c++ strings 开发者_JS百科from the commandline like in Java?

public static void main(String[] args)

where args is an array of C++ strings?


Not precisely but you can come close easily.

#include <iostream>
#include <vector>
#include <string>

using namespace std;

typedef vector<string> CommandLineStringArgs;

int main(int argc, char *argv[])
{
    CommandLineStringArgs cmdlineStringArgs(&argv[0], &argv[0 + argc]);

    for (int i = 0; i < cmdlineStringArgs.size(); ++i)
    {
        cout << cmdlineStringArgs[i] << endl;
    }

    return 0;
}

This just uses the overloaded constructor for std::vector that takes a begining/ending iterator pair to copy the command line arguments into the vectors. It is much the same as java from there on.

You can likewise build and object around that vector with utility methods to convert arguments but there is almost no point. Also there are plenty of packages with object that deal with interpreting command line switches and such. ACE, POCO, QT, etc.. all come with such facilities.


You can use a vector to get the char array into strings.

#include <vector>
#include <string>
using namespace std;

int main (int argc, char** argv)
{
    vector <string> args (argv, argv + argc);
}


Yes the main function can take 2 arguments

int main(int argc, char* argv[])

Where argc is the number of arguments and argv contains a list of the arguments.

For example if you run your program as:

MyProgram.exe hello

Then

argc = 2
argv[0] = MyProgram.exe
argv[1] = "hello"


Not built in to the language, but its very easy to implement:

#include <vector>
#include <string>
using namespace std;

int main( int argc, char *argv[] ) {
    vector <string> args;
    for ( int i = 0; i < argc; i++ ) {
        args.push_back( argv[i] );
    }
    // do something with args
}


In C, your main function signature looks like this:

int main(int argc, char** argv).

argc contains the number of arguments passed in by the command line. The name of the executable is in position 0, and adds one to argc.

argv contains an array of strings containing the arguments. Again, position 0 is the name of the executable.


The standard C++ main() signature is

int main(int argc, char* argv[])

where argc denotes the count of commandline arguments and argv[] is an array of primitive C strings holding the commandline arguments. argv[0] is the executable, as invoked from the commandline.


If you are writing a win32 application, you can use GetCommandLineW http://msdn.microsoft.com/en-us/library/ms683156(VS.85).aspx and CommandLineToArgW http://msdn.microsoft.com/en-us/library/bb776391(VS.85).aspx

There is a comment on the CommandLineToArg page about special handling that is needed if your executable has spaces in the path and there are no arguments that you might have to handle.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜