How to use an array of structures in C Programming

/*
* Program to use arrays of structures
* From the book: C Programming Visual Quickstart Guide
*
* Structures, just like integers, floats,
* and characters, can be used in arrays.
* This program creates a list of student
* names and gradesby taking input from 
* the user and storing it in an array
* of structures.
*/

#include <stdio.h>
/* 
* In order to use the strncpy() function,
* the string.h file must be included.
*/
#include <string.h>

/*
* Define two macro constants. The first 
* represents the maximum string length
* (for a person's first and last names.)
* The second will be the number of 
* elements in the array.
*/

#define STR_LEN 20

#define NUM_STUDENTS 10

int main (void) {

/*
* Define the structure. The structure
* has two character arrays and one float.
*/

struct student_grade {
char first_name[STR_LEN];
char last_name[STR_LEN];
float grade;
};

/*
* Use typedef to rename the structure 
* syntax, then create an array of 
* structures. The typedef simplififes
* the process of referring to a structure.
* Then an array of structures called class
* is created.
*/

typedef struct student_grade sg;

/*
* Create an array of structures.
*/

sg class[NUM_STUDENTS];

/* 
* Need some counters.
*/

int i, num;
int count =0;

/*
* Need some strings to handle the input.
*/

char classname[12], fn[STR_LEN], ln[STR_LEN];

/*
* Need a temporary float.
*/

/*
* grade
*/

float g;

/* 
* Prompt the user.
*/

printf("Enter the classname (without spaces): ");
scanf("%11s", classname);

/* 
* Loop to read in all the student data.
*/

for(i = 0; i < NUM_STUDENTS; ++i) {

/*
* Prompt the user.
*/

printf("Enter the student's name and their grade. Enter 0 0 0 to quit.\n(First Last ##.#): ");

/*
* Read in the input.
*/

num = scanf("%11s %11s %f", fn,ln, &g);

/*
* Check if the user is done.
*/

if(fn[0] == '0') {
break;
}

/*
* Handle the input.
*/

if(num == 3) {

strncpy(class[i].first_name, fn, STR_LEN-1);

class[i].first_name[STR_LEN-1] = '\0';

strncpy(class[i].last_name, ln, STR_LEN-1);

class[i].last_name[STR_LEN-1] = '\0';

class[i].grade = g;
++count;

/*
* Improper input format.
*/
} else {

printf("The data was not in the proper format.\n");
break;
}
}

/*
* Print the data.
*/

printf("Students and grades for the class '%s':\n", classname);

for(i = 0; i < count; ++i) {

printf("%s %s %0.1f\n", class[i].first_name, class[i].last_name, class[i].grade);
}

/*
* Pause.
*/

getchar();
getchar();
return 0;

}

Leave a Reply

Your email address will not be published. Required fields are marked *