I'm currently trying to make a small application that performs different duties. Right now I have a console app pop up and ask what I want to do, but sometimes I would rather just launch it with something like MyApp.exe -printdocuments or some such thing.
Are there any tutorials out there that can show me a simple example of this?
-
In C++, your
main()function can haveargcandargvparameters, which contain the arguments passed on the command line. Theargcis the count of arguments (including the executable name itself), andargvis an array of pointers to null-terminated strings of lengthargc.For example, this program prints its arguments:
#include <stdio.h> int main(int argc, char *argv[]) { for (int i = 0; i < argc; i++) { printf("argv[%d]: %s\n", i, argv[i]); } return 0; }Any C or C++ tutorial will probably have more information on this.
-
your entry point method i.e. in C++ your main method needs to look like
int main ( int argc, char *argv[] );you can read this article and accomplish what you are trying to do
-
You would do well to use a library for this. Here are a few links that might get you started on command line arguments with c++.
-
You can use boost::program_options to do this, If you don't want to use boost library, you must parse main function arguments by yourself.
-
getoptis a posix function (implementations for windows exist) that can help you parse your arguments:#include <unistd.h> // getopt // call with my_tool [-n] [-t <value>] int main(int argc, char *argv[]) { int opt; int nsecs; bool n_given = false, t_given = false; // a colon says the preceding option takes an argument while ((opt = ::getopt(argc, argv, "nt:")) != -1) { switch (opt) { case 'n': n_given = true; break; case 't': nsecs = boost::lexical_cast<int>(optarg); t_given = true; break; default: /* '?' */ std::cerr << "Usage: " << argv[0] << " [-t <value>] [-n]\n"; return 1; } } return 0; }
0 comments:
Post a Comment