SmRndGuy
SmRndGuy

Reputation: 1819

Making command-line programs with arguments

I discovered that it is possible to create command-line programs via C++. I am a C++ rookie and I know only basic things, but still, I want to use it to create new command-line programs.
Now, I have discovered this code:

//file name: getkey.exe
#include <conio.h>
int main(){
    if (kbhit())  return getche() | ('a' - 'A');
}

which surprisingly simple, and it runs like this: getkey
But it doesn't explain how to create a command with arguments (like: getkey /? or /K or /foo...)

How to create a command-line program with arguments? << Main question

Upvotes: 2

Views: 3855

Answers (3)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153792

You'd just want a different declaration of main():

#include <iostream>
int main(int ac, char* av[]) {
{
    std::cout << "command line arguments:\n";
    for (int i(1); i != ac; ++i)
        std::cout << i << "=" << av[i] << "\n";
}

Upvotes: 5

hmjd
hmjd

Reputation: 121961

To process command line arguments change:

int main()

to

int main(int argc, char** argv)

argc is the number of command line arguments (the number of elements in argv). argv is the command line arguments (where the first entry in argv is the name of program executable).

Upvotes: 3

Drew Dormann
Drew Dormann

Reputation: 63704

define the function main as taking these two arguments:

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

argc will be populated with the number of arguments passed and argv will be an array of those parameters, as null-terminated character strings. (C-style strings)

The program name itself will count as the first parameter, so getkey /? will set argc to 2, argv[0] will be "getkey" and argv[1] will be "/?"

Upvotes: 4

Related Questions