Concept
How do argc and argv provide and convert command-line arguments?
ComputerScienceOne / The cmain() Function
"In addition, our main() function has two arguments : argc and argv which serve to communicate any command line arguments provided to the program (review Section 2.4.4 for details). The first, argc is an integer that indicates the number of arguments provided including the executable file name itself. The second, argv actually stores the arguments as strings. We will understand the syntax later on, but for now we can at least understand how we might convert these arguments to different types such as integers and floating point numbers. Recall that argv is the argument vector : it is an array (see Chapter 20) of the command line arguments. To access them, you can index them starting at zero, the first being argv[0] , the second argv[1] , etc. (the last one of course would be at argv[argc-1] ). The first one is always the name of the executable file being run. The remaining are the command line arguments provided by the user. To convert them you can use two different functions, atoi() and atof() which are short for a lphanumeric to i nteger and f loafing-point number respectively. An example:\n\n1 //prints the first command line argument:\n\n2 printf(\"%s\n\n\", argv[0]);\n\n3 //converts the \"second\" command line argument to an integer\n\n4 int x = atoi(argv[1]);\n\n5 //converts the \"third\" command line argument to a double:\n\n6 double y = atof(argv[2]);"
Related Ideas
- How are command line arguments accessed and converted in Java?ComputerScienceOne · The javamain() Method
- How does a PHP script use entry points and command line arguments?ComputerScienceOne · Entry Point & Command Line Arguments
- How can you create an array of strings in C?ComputerScienceOne · Arrays of Strings
- How can quadratic-equation inputs be provided as command-line arguments?ComputerScienceOne · Computing Quadratic Roots
- How can conditionals verify the number of command line arguments?ComputerScienceOne · Life & Taxes
- How can you convert a string to a number using sscanf()?ComputerScienceOne · Conversions
- What role does the main() method play in a Java program?ComputerScienceOne · The javamain() Method
- What is the purpose of the main() method in a Java program?ComputerScienceOne · Comments