Command-line arguments: Difference between revisions
(add E example) |
m (Add C) |
||
Line 25: | Line 25: | ||
New_Line; |
New_Line; |
||
end Print_Commands; |
end Print_Commands; |
||
==[[C]]== |
|||
[[Category: C]] |
|||
==[[C plus plus|C++]]== |
==[[C plus plus|C++]]== |
Revision as of 02:46, 27 March 2007
You are encouraged to solve this task according to the task description, using any language you may know.
Retrieve the list of command-line arguments given to the program.
Example command line:
myprogram -c "alpha beta" -h "gamma"
Ada
Command line arguments are available through the pre-defined package Ada.Command_Line.
with Ada.Command_line; use Ada.Command_Line; with Ada.Text_IO; use Ada.Text_IO procedure Print_Commands is begin -- The number of command line arguments is retrieved from the function Argument_Count -- The actual arguments are retrieved from the function Argument -- The program name is retrieved from the function Command_Name Put(Command_Name & " "); for Arg in 1..Argument_Count loop Put(Argument(Arg) & " "); end loop; New_Line; end Print_Commands;
C
C++
Command line arguments are passed to main. Since the program name is also passed as "argument", the provided count is actually one more than the number of program arguments. Traditionally the argument count is named argc and the array of argument strings is called argv, but that's not mandatory; any (non-reserved) name will work just as well. It is, however, a good idea to stick to the conventional names.
#include <iostream> int main(int argc, char* argv[]) { std::cout << "This program is named " << arg[0] << "\n"; std::cout << "There are " << argc-1 << " arguments given.\n"; for (int i = 1; i < argc; ++i) std::cout << "the argument #" << i << " is " << argv[i] << "\n"; }
E
interp.getArgs()
Perl
Interpreter: Perl v5.x
@ARGV is the array containing all command line parameters
my @params = @ARGV; my $second = $ARGV[1]; my $fifth = $ARGV[4];
Python
argv in the sys module is a list containing all command line parameters, including the program name.
import sys program_name = sys.argv[0] # gets the program name all_arguments = sys.argv[1:] # arguments, excluding the program name
Tcl
The pre-defined variable argc contains the number of arguments passed to the routine, argv contains the arguments as a list. Retrieving the second argument might look something like this:
if { $argc > 1 } { puts [lindex $argv 1] }
(Tcl counts from zero, thus [lindex $list 1] retrieves the second item in the list)
UNIX Shell
Bourne Shell
To retrieve the entire list of arguments:
WHOLELIST="$@"
To retrieve the second and fifth arguments:
SECOND=$2 FIFTH=$5