Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ command line strings like Java?

Tags:

c++

Is there a way to get c++ strings from the commandline like in Java?

public static void main(String[] args)

where args is an array of C++ strings?

like image 514
Translucent Pain Avatar asked Nov 27 '22 22:11

Translucent Pain


1 Answers

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.

like image 183
Duck Avatar answered Nov 30 '22 23:11

Duck