Logo

Programming-Idioms

  • C
  • Java
  • Php

Idiom #60 Read command line argument

Assign to x the string value of the first command line parameter, after the program name.

$x = $argv[1];
void main(int argc, char *argv[])
{
    char *x = argv[1];
}

argv[0] would be the program name. See §5.1.2.2.1 Program startup in linked doc n1570.pdf .
String x = args[0];

This works only in method main(String[] args) .
public static void main(String[] args) {
    if (args.length != 0) {
        String x = args[0];
    }
}

In most JVM implementations, the `args` parameter will be non-null.
int main(int argc, char *argv[])
{
 vector<string> args(1 + argv, argc + argv);

 string x = args.at(0);
}

Notice that this version checks for errors (and throws if args[0] does not exist).

New implementation...
< >
programming-idioms.org