简体   繁体   中英

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?

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

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

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM