CS211: (Appendix) Command-line Arguments
Table of Contents
Introduction
Oftentimes you'll want to write programs that take input directly from the user. One way to accomplish that is to take in arguments from the command line—i.e. directly from the terminal itself. It's actually rather simple to do so.
Taking Command-line Arguments
As part of the hosted environment specification the C programming language provides rules for taking in command line arguments. These come in the form of standard arguments for the main function. The syntax is as follows:
int main(int num_of_args, char* string_of_args[])
For example, if I want to define a function called hello.c which will say "Hello" to every name given in the command line, I could write the following:
1: #include <stdio.h> 2: int main(int argc, char* argv[]){ // argc and argv are conventional names, but not required 3: for(int i = 1; i < argc; i++){ 4: printf("Hello, %s!\n", argv[i]); 5: } 6: }
Then I can compile and run it with three arguments:
josephraskind@stargazer:/tmp/cli$ gcc args.c -o ./hello_args; ./hello_args Marx Engels Lenin Hello, Marx! Hello, Engels! Hello, Lenin!
One thing you'll have noticed is I started i with 1 instead of 0. Why? Well, that's because argv[0] is always set to the name of the executable as it is the first string on the command line.
Converting Command-line Arguments
Command line arguments are always strings (char * in C). This means you must convert them if you want to take in numbers to perform calculations. For example, if I want to write a program that calculates standard deviation:
1: #include <math.h> 2: #include <stdio.h> 3: #include <stdlib.h> 4: 5: int main(int argc, char* argv[]){ 6: int size = argc - 1; 7: double mean; 8: double sum; 9: double elements[size]; 10: for(int i = 1; i < argc; i++){ 11: elements[i-1] = atof(argv[i]); // Converting the string to a double 12: sum += elements[i-1]; 13: } 14: mean = sum / size; 15: sum = 0; 16: for(int i = 0; i < size; i++){ 17: sum += pow(elements[i] - mean, 2); 18: } 19: double std = sqrt(sum/size); 20: printf("mean: %.2f\n std: %.2f\n", mean, std); 21: } 22:
josephraskind@stargazer:/tmp/cli$ gcc std.c -lm -o std; ./std 1 2 3 mean: 2.00 std: 0.82
Common functions for string conversions are listed below for reference (all are declared in stdlib.h):
atoi(str)- String to int
atol(str)- String to long
atof(str)- String to double