Search code examples
c++commandcmdcreation

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


Solution

  • 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 "/?"