Command-Line Arguments


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.

1. 3

2. ./copy

3. infile

4. outfile


6. undefined

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.

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.

Slides ( / )

study50 slide
study50 slide
study50 slide
study50 slide



echo is a Unix command, that, according to its manual page, "display[s] a line of text." For example: (~): echo This is CS50
This is CS50

Implement your own version of the echo command. You’ll want to loop through the user’s arguments and print them out one-by-one, adding a space between them. You may want to try the echo command on your Appliance first, to get a taste of how it works.

PS: In CS50 Run, you can pass command line arguments to the program you’re running by selecting the gear icon at the top of the widget.

Try out some pseudocode here!
#include <stdio.h>

int main(int argc, char** argv)
    // TODO

Tallying the Arguments


Write a program that prints out the total number of characters in the command line arguments given to the program. Ignore whitespace (for example, spaces, newlines, and tab characters), and ignore the program name. For example:

  • ./a.out foo should indicate that 3 characters were given.

  • ./a.out foo bar baz should indicate that 9 characters were given.

  • ./a.out should indicate that 0 characters were given.

Remember, you can pass arguments using the code widget by clicking on the gear icon!

Try out some pseudocode here!

int main(int argc, string argv)

    // TODO



study50 video thumbnail

Week 2, Wednesday

An introduction to command-line arguments
study50 video thumbnail

Christopher's Command-Line Arguments Short

Christopher gives a general overview