Pure Programmer
Blue Matrix


Cluster Map

Command Line Arguments

L1

This page is under construction. Please come back later.

When running programs from the command line we have the option of supplying additional information in the form of arguments on the command line. Command line arguments take the form of strings separated by spaces. For example the following command line program invokation has three additional arguments.

$ swift Program.swift Fred 123 Flintstone

In our programs we can access each of these arguments using the variables Process.arguments[0], Process.arguments[1], Process.arguments[2], etc. The program name can be found in the variable with the 0 subscript. The user supplied arguments are in the variables with subscripts 1, 2, 3, etc.

CmdLineArgs1.swift
#!/usr/bin/env swift;
import Foundation
import Utils

func main() -> Void {
	print("Number of arguments: " + String((CommandLine.arguments.count - 1)))
	print("Program Name: " + CommandLine.arguments[0])
	print("Arg 1: " + CommandLine.arguments[1])
	print("Arg 2: " + CommandLine.arguments[2])
	print("Arg 3: " + CommandLine.arguments[3])
	print("Arg 4: " + CommandLine.arguments[4])
	exit(EXIT_SUCCESS)
}
main()

Output
Number of arguments: 4 Program Name: ./CmdLineArgs1 Arg 1: Fred Arg 2: Barney Arg 3: Wilma Arg 4: Betty Number of arguments: 4 Program Name: ./CmdLineArgs1 Arg 1: Φρειδερίκος Arg 2: Барнеи Arg 3: ウィルマ Arg 4: 贝蒂

If we want to treat a command line argument as a number we first need to convert from the string representation passed on the command line to a numeric type. This is where conversion functions come in handy. The example below illustrates how to convert command line arguments to integers.

CmdLineArgs2.swift
#!/usr/bin/env swift;
import Foundation
import Utils

func main() -> Void {
	let a:Int32 = Int32(CommandLine.arguments[1]) ?? 0
	let b:Int32 = Int32(CommandLine.arguments[2]) ?? 0
	let c:Int32 = a + b
	print(Utils.format("{0:d} + {1:d} = {2:d}", a, b, c))
	exit(EXIT_SUCCESS)
}
main()

Output
326 + 805 = 1131

The example below converts the command line arguments to floating point values.

CmdLineArgs3.swift
#!/usr/bin/env swift;
import Foundation
import Utils

func main() -> Void {
	let a:Double = Double(CommandLine.arguments[1]) ?? 0.0
	let b:Double = Double(CommandLine.arguments[2]) ?? 0.0
	let c:Double = a + b
	print(Utils.format("{0:f} + {1:f} = {2:f}", a, b, c))
	exit(EXIT_SUCCESS)
}
main()

Output
3.210000 + 7.010000 = 10.220000

Questions

Projects

More ★'s indicate higher difficulty level.

References