Presentation is loading. Please wait.

Presentation is loading. Please wait.

Command-line Arguments

Similar presentations


Presentation on theme: "Command-line Arguments"— Presentation transcript:

1 Command-line Arguments
int main(void) int main(int argc, string argv[]) Programs, like functions, can take in arguments. Thus far, we haven't passed any arguments to main, and have declared it like this: int main(void) However, we can also declare main like this: int main(int argc, string argv[]) The parameters argc and argv provide a representation of the program's command line. argc is the number of strings that make up the command line (including the program name), and argv is an array that contains those strings.

2 Test Yourself jharvard@appliance (~): ./copy infile outfile
1. What is argc? 2. What is argv[0]? 3. What is argv[1]? 4. What is argv[2]? 5. What is argv[3]? 6. What is argv[4]? (~): ./copy infile outfile 1. 3 2. ./copy 3. infile 4. outfile 5. NULL 6. undefined

3 Mario Revisited jharvard@appliance (~): ./mario 10
Remember mario.c from pset 1? What if we modified the problem specification so that the program must read the pyramid height from the command line? Now, instead of prompting the user to enter a height using printf() and GetInt(), the user simply enters height on the command line. ./mario 10 should result in the printing of a pyramid of height 10.

4 int main(int argc, string argv[]) { if (argc != 2)
printf("Usage: mario height"); return 1; } int height = atoi(argv[1]); // etc . . . First, check for correct usage by ensuring that only two command line arguments were entered (the program name and the pyramid's height). If argc != 2, instruct the user regarding correct usage and quit the program. Note the use of the function atoi(). atoi() converts ASCII strings to integers. That is, the command line string "10" becomes the integer value 10. So instead of relying on GetInt() to provide user input, we can now take the value supplied by the user on the command line to use as height.


Download ppt "Command-line Arguments"

Similar presentations


Ads by Google