Answer on Question #48489 – Programming - C
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char name[20];
char answer[21];
int score;
char grade;
} student;
int main() {
student **array = NULL, **temp_array = NULL;
student *curr_stud = NULL;
FILE* file;
char filename[200];
char answer[20];
double grade;
int i, students_count = 0, array_size = 0;
char result = 0;
while (true) {
printf("Enter filename: ");
scanf("%s", filename);
file = fopen(filename, "r");
if (file == NULL) {
printf("Error opening file!\n");
} else {
break;
}
}
for (i = 0; i < 20; i++) {
fscanf(file, "%c", answer + i);
}
while (feof(file) == 0) {
if (students_count == array_size) {
array_size += 5;
temp_array = (student**)malloc(array_size * sizeof(student*));
for (i = 0; i < students_count; i++) {
temp_array[i] = array[i];
}
free(array);
array = temp_array;
}
curr_stud = (student*)malloc(sizeof(student));
if (fscanf(file, "%s", curr_stud->name) < 1) break;
else {
curr_stud->score = 0;
fgetc(file);
for (i = 0; i < 20; i++) {
curr_stud->answer[i] = fgetc(file);
if (curr_stud->answer[i] != ' ') {
if (curr_stud->answer[i] == answer[i])
curr_stud->score += 2;
else
curr_stud->score -= 1;
}
}
curr_stud->answer[20] = '\0';
grade = curr_stud->score / (20 * 2.0);
if (grade >= 0.9) curr_stud->grade = 'A';
else if (grade >= 0.8) curr_stud->grade = 'B';
else if (grade >= 0.7) curr_stud->grade = 'C';
else if (grade >= 0.6) curr_stud->grade = 'D';
else curr_stud->grade = 'F';
array[students_count++] = curr_stud;
}
}
fclose(file);
for (i = 0; i < students_count; i++) {
printf("%s - %s - %d - %c\n", array[i]->name, array[i]->answer, array[i]->score, array[i]->grade);
}
printf("Save result? (y\n) ");
getchar();
scanf("%c", &result);
if (result == 'y' || result == 'Y') {
while (true) {
printf("Enter filename: ");
scanf("%s", filename);
file = fopen(filename, "w+");
if (file == NULL) {
printf("Error opening file!\n");
} else {
break;
}
for (i = 0; i < students_count; i++) {
fprintf(file, "%s - %s - %d - %c\n", array[i]->name, array[i]->answer, array[i]->score, array[i]->grade);
}
fclose(file);
}
for (i = 0; i < students_count; i++) {
free(array[i]);
}
free(array);
}
}http://www.AssignmentExpert.com/
Comments