Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- // Data model
- typedef struct {
- struct student *next;
- int id;
- char name[20];
- int age;
- } student;
- // Smth like constructor
- student frst = {NULL, -1, "_SERVICE_ELEM", 0};
- student *first = &frst, *last = &frst;
- // Free memory recursively
- void cleanup(student *start)
- {
- if (start->next != NULL) {
- cleanup(start->next);
- }
- printf("Cleaned id: %d name: %s\n", start->id, start->name);
- free(start);
- start = NULL;
- }
- // Data output
- void print()
- {
- student *ptr = first->next;
- printf("\nList of students:\n");
- while (ptr != NULL)
- {
- printf("%d Student %s is %d years old\n", ptr->id, ptr->name, ptr->age);
- ptr = ptr->next;
- }
- }
- // Generate new data element
- void add(const char *name, const int age)
- {
- last->next = (student *)malloc(sizeof(student));
- ((student *)(last->next))->id = last->id + 1;
- last = last->next;
- last->next = NULL;
- strcpy(last->name, name);
- last->age = age;
- }
- // Add new student
- void new_student()
- {
- char name[20] = { 0 };
- int age = 0;
- printf("Enter the student name: ");
- scanf("%19s", name);
- printf("Enter the student age: ");
- scanf("%d", &age);
- add(name, age);
- }
- // Start
- int main()
- {
- while (1)
- {
- printf("Add new student?(yes/no): ");
- char str[4]; scanf("%3s", str);
- if (!strcmp(str, "no") || !strcmp(str, "n")) {
- if (first->next == NULL) {
- printf("No one row was created!");
- }
- else {
- print();
- }
- break;
- }
- else if (!strcmp(str, "yes") || !strcmp(str, "y")) {
- printf("\n");
- new_student();
- printf("\n");
- continue;
- }
- else {
- printf("Error in the input, try again\n");
- continue;
- }
- }
- printf("\n");
- cleanup(first);
- printf("\n");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement