/* * struct.c -- practice with structures in C. A structure is a * special data type, similar to the data attributes of a Java or C++ class. * A single structure usually consists of several fields of different * basic types, such as 3 integers, a string and a floating-point number. */ #include #include #include struct student { char name[30]; int midterm; int final; int term_paper; double average; }; int get_input(struct student []); void compute_averages (struct student[], int); void output (struct student[], int); main() { struct student my_class[20]; int num_students; num_students = get_input (my_class); compute_averages (my_class, num_students); output (my_class, num_students); } /* * the get_input() function reads lines from standard input, * and updates corresponding fields of each student. The function * returns the number of students. * * The condition "feof (stdin)" tests to see if we have reached the * end of standard input. * * C does not have a string type. I'm declaring the line to be an array * of up to 82 characters. Why 82? Because I want to allocate enough * space for up to 80 characters on a line, plus the newline character, * plus the null character that must appear at the end of a string in C. * In practice, however, our lines won't be this long! * * It is a good idea to use fgets() to read a line of text. It takes * 3 parameters: the name of the "string" variable, the maximum size, * and the file you are reading from. If that "file" is actually just * interactive input, then say stdin, which stands for "standard input." */ int get_input(struct student class[]) { int i; char input_line[82]; for (i = 0; ; ++i) { fgets(input_line, 82, stdin); if (feof (stdin)) break; strcpy (class[i].name, strtok(input_line, ":")); class[i].midterm = atoi (strtok (0, " ")); class[i].final = atoi (strtok (0, " ")); class[i].term_paper = atoi (strtok (0, " ")); } return i; } void compute_averages (struct student class[], int num_students) { } void output(struct student class[], int num_students) { int i; for (i = 0; i < num_students; ++i) printf ("%-20s %3d %3d %3d %5.1f\n", class[i].name, class[i].midterm, class[i].final, class[i].term_paper, class[i].average); }