CSC 101 Lab Week 7
Using Struct and Command-Line Arguments




ISSUED:
Friday, 4 May 2012
DUE: Wednesday, 11 May 2012, by the end of lab
POINTS POSSIBLE: 1
WEIGHT: 1% of total class grade

Specification

Write a program that uses the following struct to hold information about a student:

typedef struct {
    char last_name[NAME_LEN];
    int id;
    char major[MAJOR_LEN];
} StudentInfo;

The program declares a variable s of this type. The program gets values for the data fields of s in one of two different ways:

  1. If the program is executed with no command-line arguments, then the program prompts for the information and reads the values from standard inpout (using scanf). These input values are stored into the three fields of the variable s.

  2. If there are exactly three command-line arguments, then the program stores those three values into the fields of the variable s.

If there are a different number of command-line arguments than zero or three, the program outputs the error message "Program must have 0 or 3 arguments".

After the values are stored into the variable s, they are output to standard output. The output format is shown in the sample outputs below.

Name the program student_info.c and compile with the command

gcc -ansi -pedantic -Wall -Werror -g student_info.c -o student_info

Here is a sample of running the program with input from stdin:

unix1: student_info
Input last name, id, and major: Smith 12345678 CSC
Last Name: Smith
Id: 12345678
Major: CSC

Here is a sample run with three command-line arguments:

unix1: student_info Smith 12345678 CSC
Last Name: Smith
Id: 12345678
Major: CSC

Finally, here is a sample run with an incorrect number of arguments:

unix1: student_info Smith
Program must have 0 or 3 arguments.

Reading Resources

Section 13.7 of the book describes how to use command-line arguments in the main function. Since command-line arguments are string values, you will need to use the atoi function to convert the string value of the student id into an int. The atoi function has this signature:

int atoi(const char* s);
It returns the integer value of the string s. If s is not a legal string, it returns 0.

There is a simple example of using command-line arguments and atoi in the lab7 directory, in the file cmd-line.c unix1: student_info Smith Program must have 0 or 3 arguments.

Submitting Your Work

Sometime before end of lab on Wednesday May 16, demonstrate that your program runs correctly. To verify that you've completed the lab, submit your work as follows:

handin gfisher 101_lab7 student_info.c