'How to scan multiple strings in one place? [closed]
I am working on a project. I need to get each student's courses and their number, for example:
Lisa Miller 890238
Mathematics MTH345
Physics PHY357
ComputerSci CSC478
History HIS356
I do not know how to register all those courses and their numbers in one place specified for that student. What should I do?
Solution 1:[1]
It looks like you need two structures:
One for the student and their list of courses, and one for a course.
Assuming you know maximum number of courses a student can take:
struct course {
char name[MAX_COURSE_NAME_LEN];
char id[MAX_COURSE_ID_LEN]; //this one should be 7
};
struct student {
char name[MAX_STUDENT_NAME_LEN];
unsigned int id; //student ids are all numbers, right?
int num_courses; //number of courses student actually takes
struct course courses[MAX_COURSES];
}
If you want to be memory efficient or the maximum number of courses a student can take is not specified, you should used a linked list of courses instead of an array.
You will need custom code to read this from file and write it back to a file.
C standard library does not come with serialization and deserialization functions, but if this is more than a homework project, you may want to look for a dedicated serialization library.
Solution 2:[2]
Here are steps you can follow:
- define a structure for student courses with these fields:
- a pointer to the next student course
- a pointer to the course name
- a string for the course ID
- define a structure for the student with these fields:
- a pointer to the next student
- a string pointer for their name
- an integer for their student ID
- a pointer to a list of courses
- define a pointer to a list of students, initialized to
NULL - in a loop: read the file one line at time
- trim trailing spaces
- locate the last word
- if it starts with a digit:
- allocate a new student structure and link it at the end of the student list.
- convert the number as the student number using
strtoul() - copy the beginning of the line as the student name using
strdup()
- otherwise the line is a course:
- allocate a new student course and link it at the end of the current student's course list
- copy the word as the course ID using
sscanf() - copy the beginning of the line as the course name using
strdup()
Constraints:
- do not use
strtok() - do not use
strcpy() - prevent all buffer overflows
- detect malformed input and output a meaningful error message
You can write a printing routine to print the complete student list and compare the output with the file contents for validation.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | chqrlie |
