So I'm working on a program in C where I take input from a file and put it in an array of Structs ... however never having gotten input from a file in C before, I'm a bit confused. I've tried multiple ways of doing it, and all of them came with a pretty similar result: The first variable is fine, the second variable is fine (except only half of the name is copied), the third and fourth variable are random gibberish. How big the gibberish is depends on how I write the program, but it is always random characters.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student {
int student_ID;
char name[26];
char degree[26];
char campus[26];
};
void main() {
FILE* fileToOpen = fopen("student database.txt", "r");
if (fileToOpen == NULL) {
printf("File cannot be opened!...\n...");
exit(0);
}
struct student studentList[12];
char buffer[200];
fgets(buffer, 200, fileToOpen);
int counter = 0;
int value;
while (!feof(fileToOpen)) {
value = sscanf(buffer, "%d,%s,%s,%s", &studentList[counter].student_ID, &studentList[counter].name, &studentList[counter].degree, &studentList[counter].campus);
printf("Read point: %d %s\n", studentList[counter].student_ID, studentList[counter].name);
fgets(buffer, 200, fileToOpen);
counter++;
}
printf("\n\n\n");
printf("First point: % d % s % s % s\n", studentList[0].student_ID, studentList[0].name, studentList[0].degree, studentList[0].campus);
printf("Second point: % d % s % s % s\n", studentList[1].student_ID, studentList[1].name, studentList[1].degree, studentList[1].campus);
printf("\nvalue: %d", value);
fclose(fileToOpen);
}
I don't get what's going on here. I've tried other input methods (ones that iddn't involve that char buffer array, fgets, etc), followed guides step by step, yet the print statements always revealed that only part of the data is input correctly is the first variable, and half of the second variable (first name). You can see that in the final two print statements. What's the problem?
Here is the text file for reference:
895329,Tom Elder,Computer Science,Downtown Campus
564123,Elissa Honk,Interior Design,East Campus
963474,Alfonso Dobra,Civil Engineering,West Campus
127485,Paolo Morisa,Accounting,West Campus
330021,Lisa Bali,Accounting,Downtown Campus
844112,Eli Dovian,Computer Science,East Campus
745112,Rola Etrania,Civil Engineering,East Campus
541247,Pamela Dotti,Interior Design,East Campus
745930,Paul Sabrini,Accounting,Downtown Campus
500124,Gabriella Alma,Accounting,Downtown Campus
741206,Joe Damian,Computer Science,West Campus
963100,Perla Kino,Interior Design,East Campus
Thanks for any help and advice. This is all the program is so far.