C ++ command line strings like Java?

Is there a way to get C ++ strings from the command line, for example in Java?

public static void main(String[] args)

where args is an array of C ++ strings?

+3
source share
7 answers

Not exactly, but you can easily come up.

#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;
}

It just uses an overloaded constructor for std :: vector, which takes an iterator initialization / end pair to copy command line arguments to vectors. This is the same as java from here.

You can also create and create objects around this vector using utility methods for converting arguments, but there is almost no point. There are also many packages with objects that deal with the interpretation of command line keys, etc. ACE, POCO, QT, etc. Everyone has such opportunities.

+9

, char .

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

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

, 2

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

argc - , argv .

, :

MyProgram.exe hello

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

, :

#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
}
+1

C :

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

argc , . 0 argc.

argv , . , 0 - .

0

++ main()

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

argc , argv[] - C, . argv[0] - , .

0

All Articles