Adding parameters for a program at launch - c++

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 have argc and argv parameters, which contain the arguments passed on the command line. The argc is the count of arguments (including the executable name itself), and argv is an array of pointers to null-terminated strings of length argc.
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.

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.

getopt is 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;
}

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++.
gperf

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

Related

Command line parameters c++ [duplicate]

How do I read command-line parameters in C? For example, in
./test --help
or
./test --build
how do I access "--build" or "--help"?
Your parameters are in argv:
int main(int argc, char **argv)
if you printf the content of argv (argv[0],argv[1] etc) youll get the idea.
try:
int main (int argc, char **argv)
{
for(int i = 0;i< argc;i++)
printf("%s\r\n",argv[i]);
}
You can use the argc and argv arguments to the main function and do different things based on them:
#include <string.h>
void dohelp(void) { /* whatever; */ }
void dobuild(void) { /* whatever; */ }
int main(int argc, char **argv) {
if (argc == 2) {
if (!strcmp(argv[1], "--help")) dohelp();
if (!strcmp(argv[1], "--build")) dobuild();
}
return 0;
}
argc contains the number of parameters passed by the shell to your program, including the program name. So myapp --help gets an argc of 2.
argv are the arguments themselves. The last argv (argv[argc]) is the NULL pointer.
Edit: the parameters don't need to be named argc and argv, but naming else something else is very, very bad!
int main(int foo, char **bar) /* RGAGGGGHH */
int main(int n, char **options) /* RGAGGGGHH */
The very basic is to use the arguments (int argc, char *argv[]) and you can parse those directly.
One more advanced method is to use getopt... http://www.gnu.org/s/libc/manual/html_node/Getopt.html
Command line arguments are arguments passed to your program with its name. For example, the UNIX program cp (copies two files) has the following command line arguments:
cp SOURCE DEST
You can access the command line arguments with argc and argv:
int main(int argc, char *argv[])
{
return 0;
}
argc is the number of arguments, including the program name, and argv is the array of strings containing the arguments. argv[0] is the program name, and argv[argc] is guaranteed to be a NULL pointer.
So the cp program can be implemented as such:
int main(int argc, char *argv[])
{
char *src = argv[1];
char *dest = argv[2];
cpy(dest, src);
}
They do not have to be named argc and argv; they can have any name you want, though traditionally they are called that.
There are several ways to do it [as usual].
Command line arguments are read from argv (passed to main along with argc).
You can parse those yourself and have a bit switch setting flags each time a new option is found in argv. Or you can use a library to parser command line arguments. I suggest libc getopt (google it).

printf causes crash

#include <stdio.h>
int main(char sendbuf[100])
{
printf (sendbuf);
return 0;
}
Somehow this very basic program crashes when I try to use it, it's meant to print up whatever is typed as a parameter. If I remove the line "printf (sendbuf);" the crash goes away.
The first argument to main is the number of parameters. The second argument is an array of strings. The first element (index 0) of the second argument is the name of your program:
#include <stdio.h>
int main(int c, char **argv)
{
printf ("%s\n", c > 1 ? argv[1] : "No Argument");
return 0;
}
Your first parameter must be an integer, not a char array. Here is the right program:
#include <stdio.h>
int main(int argc, char* argv[])
{
if (argc > 1) {
printf( argv[1] );
}
else {
printf( "No arguments provided" );
}
return 0;
}
argv[0] is your program name, so argv[1] is the first parameter provided on teh command line.
C supports two forms of main function:
int main() { /* ... */ }
and
int main(int argc, char* argv[]) { /* ... */ }
To take parameter from main, you need to change your code to:
#include <stdio.h>
int main(int argc, char* argv[])
{
if (argc > 1){
printf ("%s\n", argv[0]);
}
return 0;
}
Or use stream:
#include <iostream>
int main(int argc, char* argv[])
{
if (argc > 1){
std::cout << argv[0]) << std::endl;
}
return 0;
}
argv[0] is application name, input parameters starts from argv[1] if any.
An implementation must support the following two definitions of main:
int main() { }
int main(int argc, char* argv[]) { }
It is implementation-defined whether they support any other definitions. I don't know of any implementation that allows int main(char*) though (which is what yours is equivalent to).
This will print everything you type on the command line after the program name, even with spaces. It will not crash if you type nothing after the program name.
#include <stdio.h>
int main(int argc, char **argv)
{
for(int i=1; i<=argc; ++i) {
printf("%s\n", argv[i]);
}
}

C++ CMD input along with exe

Sorry for such a noobie question, but how can I get a program to read the data i input with my program, like how cmd does it with the options
shutdown.exe -f
how do i read the example -f into my program?
This should print out each of the whitespace delimited parameters which were passed to your program.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
for(int i = 0; i < argc; i++)
{
printf("%s\n", argv[i]);
}
return 0;
}
If you're using plain old C++, your main function will need to look something like this:
int main(int argc, char *argv[])
where argc is the number of whitespace separated items, and argv is an array of pointers to each one
int main(int argc, char *argv[])
{
}
arguments are passed by argv.

How to get 1st parameter in main() in C++? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Pass arguments into C program from command line.
mypro parameter
When run like above,how to get the parameter in mypro's main() :
#include <iostream>
int main()
{
char* str = "default_parameter";
if(parameter_exists())str = parameter;
...
}
How to implement the pseudo code above?
Just need to add (int argc, char *argv[]) to your main function. argc holds the number of arguments, and argv the arguments themselves.
int main(int argc, char *argv[])
{
std::string str = "default";
if (argc > 1) { str = argv[1]; }
}
Note that the command is also included as an argument (e.g. the executable). Therefore the first argument is actually argv[1].
When expecting command-line arguments, main() accepts two arguments: argc for the number of arguments and argv for the actual argument values. Note that argv[0] will always be the name of the program.
Consider a program invoked as follows: ./prog hello world:
argc = 3
argv[0] = ./prog
argv[1] = hello
argv[2] = world
Below is a small program that mirrors the pseudocode:
#include <iostream>
#include <string>
int main(int argc, char **argv) {
std::string arg = "default";
if (argc >= 2) {
default = argv[1]
}
return 0;
}
Your function should use the second of these two allowed C++ main function signatures:
int main(void)
int main(int argc, char *argv[])
In this, argc is the argument count and argv is an argument vector.
For more details, see this Wikipedia article.
Well you need a main function that accepts arguments, like so:
int main(int argc, char *argv[])
{
}
You would then check the number of arguments passed in using argc. Usually there is always one, the name of the executable but I think this is OS dependent and could thus vary.
You need to change the main to be:
int main(int argc, char** argv){
argc is the number of paramaters, argv is an array containing all of the paramaters (with index 0 being the name of the program). Your first parameter will be located at index 1 of argv.
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
for(int i = 1; i < argc; i++)
cout << atoi(argv[i]) << endl;
return 0;
}
Here argc gives the count of the arguments passed
and argv[i] gives ith command line parameters.
where argv[0]='name of the program itself'
main has two parameters, int argc and char** argv which you can use to access to the command line parameters.
argc is the number of parameters including the name of the executable, argv points to the parameter list itself (so that argv[0] is "mypro" in your example).
Just declare main like
int main (int argc, char** argv){..}
You need to use this declaration of main:
int main(int argc, _TCHAR* argv[])
{
if (argc > 1)
{
str = argv[1];
}
}
argv[0] is the name of the executable, so the parameters start at argv[1]
On Windows, use the following signature instead to get Unicode arguments:
int wmain(int argc, wchar_t** argv)

Obtaining command line arguments in a Qt application

The following snippet is from a little app I wrote using the Qt framework. The idea is that the app can be run in batch mode (i.e. called by a script) or can be run interactively.
It is important therefore, that I am able to parse command line arguments in order to know which mode in which to run etc.
[Edit]
I am debugging using Qt Creator 1.3.1 on Ubuntu Karmic. The arguments are passed in the normal way (i.e. by adding them via the 'Project' settings in the Qt Creator IDE).
When I run the app, it appears that the arguments are not being passed to the application. The code below, is a snippet of my main() function.
int main(int argc, char *argv[])
{
//Q_INIT_RESOURCE(application);
try {
QApplication the_app(argc, argv);
//trying to get the arguments into a list
QStringList cmdline_args = QCoreApplication::arguments();
// Code continues ...
}
catch (const MyCustomException &e) { return 1; }
return 0;
}
[Update]
I have identified the problem - for some reason, although argc is correct, the elements of argv are empty strings.
I put this little code snippet to print out the argv items - and was horrified to see that they were all empty.
for (int i=0; i< argc; i++){
std::string s(argv[i]); //required so I can see the damn variable in the debugger
std::cout << s << std::endl;
}
Does anyone know how I can retrieve the command line args in my application?
If your argc and argv are good, I'm surprised this would be possible as QApplication::arguments() is extremely simple. Note the source code. Filtering the #ifdefs for Linux, it's just:
QStringList QCoreApplication::arguments()
{
QStringList list;
if (!self) {
qWarning("QCoreApplication::arguments: Please instantiate the QApplication object first");
return list;
}
const int ac = self->d_func()->argc;
char ** const av = self->d_func()->argv;
for (int a = 0; a < ac; ++a) {
list << QString::fromLocal8Bit(av[a]);
}
return list;
}
That's all you've got. There's a Unicode caveat which I would not think would apply to Karmic:
"On Unix, this list is built from the argc and argv parameters passed to the constructor in the main() function. The string-data in argv is interpreted using QString::fromLocal8Bit(); hence it is not possible to pass, for example, Japanese command line arguments on a system that runs in a Latin1 locale. Most modern Unix systems do not have this limitation, as they are Unicode-based."
You might try a copy of that code against your argc and argv directly and see what happens.
Only in order to keep response up-to-date, Qt now provides a dedicated class for parsing command line:
http://doc.qt.io/qt-5/qcommandlineparser.html
P.S. : can only post this as response and not a comment; I'm sorry because the question was not really how to parse but how to access.
If you are writing a Console only application then you might want to consider using QCoreApplication instead of QApplicition. QCoreApplication is part of QtCore while QApplication is defined in QtGui, so you get an extra and unnecessary dependency.
here is a simple example to have the arguments in a QStringList. Assuming you start the app with argument -q -t
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
QString x;
for (int i=1; i<argc; i++)
{
x.append(argv[i]);
}
qDebug() << x;
QStringList args = x.split("-");
args.removeFirst();
qDebug() << "args="<< args;
return a.exec();
}
Output is as follow
x= "-q-t"
args= ("q", "t")
Now you have the arguments as a QStringList ..
and here is a complete code i wrote and use in a small application
#include "mainwindow.h"
#include <QApplication>
#include <QDebug>
static QStringList arguments;
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
//analyze the arguments
//-b: use buidin player and if it does not exist use mpg123 shell to play files
//
//-t: test the player upon startup and exit
//-s: use the following speaker ID for the test
//-f: use the following file name and path
//syntax: example:
// -b : to use build in player
// -t -s xx:xx:xx:xx:xx -f azanfile.mp3: to test upon startup playing a file
bool useBuildInPlayer;
QString x;
for (int i=1; i<argc; i++)
{
x.append(argv[i]);
}
arguments << x.split("-"); arguments.removeFirst();
qDebug() << arguments;
if (arguments.indexOf("b")>=0)
useBuildInPlayer=true;
else
useBuildInPlayer=false;
bool TestSpeaker = false;
bool spkr=false; QString speaker;
bool playfile=false; QStringList testfiles;
QString filestring;
foreach (QString x, arguments)
{
if (x.left(1)=="s")
{
speaker = x.mid(1,-1); //remove the s from the beginning
spkr=true;
}
if (x.left(1)=="f")
{
filestring=x.mid(1,-1);
playfile=true;
testfiles<<filestring;
}
if (x=="t")
TestSpeaker = true;
}
if (TestSpeaker)
{
if (spkr)
{
qDebug() << "testing speaker "<< speaker;
}
else
{
qDebug() << "test argument needs speaker -s xx:xx:xx:xx:xx";
}
if (playfile)
{
qDebug() << "testing file "<< filestring;
}
else
{
qDebug() << "test file is missing";
}
}
if (TestSpeaker && spkr && playfile)
{
if (useBuildInPlayer) //use build in player
{
qDebug() << "testing using buildin player";
}
else // use mpg123 shell
{
qDebug() << "testing using mpg123 shell";
}
}
return a.exec();
}