[ fromfile: clargs.xml id: clargs ]
main()
is a function that is called at program startup.
If you want the program to accept command-line arguments, you must define main
with its full parameter list.
C and C++ permit some flexibility in the way that arguments are defined in main()
, so you may see it defined in a variety of ways:
int main(int argc, char* argv[]) int main(int argCount, char ** argValues) int main(int argc, char * const argv[])
Example 1.19 is a simple main
program that prints its command-line arguments.
Example 1.19. src/clargs/clargs-iostream/clargs.cpp
argv
, the argument vector, is an array (Section 21.4) that contains all the command-line strings.
argc
, the argument count, is the number of char
arrays in argv
.
main()
needs to return an int
to the parent process.
The return value should be 0 if all went well, or a nonzero error code if something went wrong.
Note | |
---|---|
Try not to confuse this interpretation of |
clargs> ./clargs spam eggs "space wars" 123 argc = 5 argv# 0 is ./clargs argv# 1 is spam argv# 2 is eggs argv# 3 is space wars argv# 4 is 123 246
In example Example 1.20, we have rewritten Example 1.19 to set up and access the command-line arguments using Qt types and avoiding the use of arrays.
The two applications produce the same output.
Example 1.20. src/clargs/qt/clargs.cpp
#include <QTextStream> #include <QCoreApplication> #include <QStringList> int main (int argc, char* argv[]) { QCoreApplication app(argc, argv); QTextStream cout(stdout); QStringList arglst = app.arguments(); cout << "argc = " << argc << endl; for (int i=0; i<arglst.size(); ++i) { cout << QString("argv#%1 is %2").arg(i).arg(arglst[i]) << endl; } int num = arglst[argc - 1].toInt(); cout << num * 2 << endl; }
Most applications that employ Qt types should define an object of type QCoreApplication or QApplication as early as possible in main()
. [9]
The QCoreApplication app
is initialized with the argument count and the argument vector.
app
silently converts the char
arrays in argv
to QStrings and stores those strings in a QStringList (Section 4.2.1).
You can then access and process the command-line arguments by using app
to call the arguments()
function.
Notice the use of the QString function toInt()
.
[9] Applications that use only types such as QString, QStringList, and QTextStream do not need a QCoreApplication.
Generated: 2012-03-02 | © 2012 Alan Ezust and Paul Ezust. |