2

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

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
SmRndGuy
  • 1,719
  • 5
  • 30
  • 49
  • 2
    Step 1: [Get a good introductory C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). Step 2: Read through said book and do the exercises. Step 3: Read up on command line arguments and how you can get them via `int main(int argc, char**argv)`. – In silico Jan 08 '12 at 00:01
  • 4
    I think what you call "CMD commands" are more commonly known as "programs". Yes, C++ is a programming language and can be used to create programs. – Kerrek SB Jan 08 '12 at 00:01

3 Answers3

5

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";
}
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
4

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

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
3

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

hmjd
  • 120,187
  • 20
  • 207
  • 252