user1041338
user1041338

Reputation:

taking command line input in different ways

How can one take command line argument by not using below structure ?

 int main ( int argc, char* argv ) {

 }

My question is really : how can I take below input :

 ./executableProgramName   inputX inputY inputZ inputT

in any function ?

in foo () {

 // what should I write so that I can get same effect 
}

Upvotes: 2

Views: 2444

Answers (4)

bames53
bames53

Reputation: 88155

The method specified by the standard for getting command line arguments is the argc and argv parameters passed to the entry point function main. There's no other standard method.

Some platforms offer non-standard methods. For example, if you're on Windows you can use GetCommandLineW

Here's an example that uses some C++11 stuff too.

#include <ShellAPI.h> // for CommandLineToArgvW
#include <string>
#include <vector>
#include <codecvt>
#include <locale>

int main() {
#ifdef WIN32
    LPWSTR *szArglist;
    int argc;
    szArglist = CommandLineToArgvW(GetCommandLineW(),&argc);
    if(NULL==szArglist) {
       std::cerr << "CommandLineToArgvW failed\n";
    }
    std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>,wchar_t> convert; // codecvt_utf8 or codecvt<char16_t,char,mbstate_t> should work (will work once the char16_t specialization of codecvt works)
    vector<string> args;
    for(int i=0;i<argc;++i) {
        args.push_back(convert.to_bytes(szArglist[i]));
    }
#endif //ifdef WIN32

}

Upvotes: 2

Khaled Alshaya
Khaled Alshaya

Reputation: 96849

Maybe the best way is to forward the handling of command line arguments into an object, or simply a function:

#include <vector>
#include <string>

void handle_commandline_args(const std::vector<std::string>& args){
    ...
}
int main(int argc, char* argv[]){
    handle_commandline_args(std::vector<string>(argv[0], argv[0] + argc));
    ...
}

Upvotes: 2

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361252

If you're working with MSVC++, then you can use below win32 API to get command line arguments anytime in your program:

However, this makes your code non-standard. So it is better if you use main(int argc, char *argv[]) to get the command line arguments and save them for later use, e.g to be used by other functions.

Upvotes: 1

jli
jli

Reputation: 6623

You can not arbitrarily get the command-line arguments from any function. In C++, the only way command-line arguments are passed in is through the char* array in the main function.

If you want them to be accessible from anywhere, consider keeping them in a global variable, or passing them into each necessary function call. For example:

int argumentCount;
char **argumentArray;

int main ( int argc, char** argv )
{
    argumentCount = argc;
    argumentArray = argv;
}

int foo()
{
    std::cout << argumentArray[0]; // or whatever
}

Upvotes: 1

Related Questions