Logo

Programming-Idioms

  • C++
  • Java
  • Dart
  • Clojure
  • Lua
  • Go
  • Python
  • Obj-C

Idiom #60 Read command line argument

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

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).
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.
String x = args[0];

This works only in method main(String[] args) .
main(args) {
  var x = args[0];
}

Command line arguments are only available as argument to main.
x = arg[1]
import "os"
x := os.Args[1]

os.Args[0] is actually the executable name.
import sys
x = sys.argv[1]

argv[0] is the program name
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 .

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