separting integer from string and storing it in a linked list.
I wrote a code that takes input from a file and stores them into a linked list.
My code stores the contents of the file into a node contains a char array.
So if I did everything right each name in the input file has it's own node and they are linked together.
However I want to separate the name and store it into a char array and separate the age and store it into an integer array.
For example Martha will be stored in the first node of the char array. Her age which is 12 will be stored in the int array of the first node. And I want to do it for all the other names.
This is what I have accomplished so far.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXN 50
#define val 2
typedef struct node {
char name[MAXN];
//int age[val];
struct node *next;
}
node;
int main (int argc, char **argv) {
FILE *file = argc > 1 ? fopen (argv[1], "r") : stdin;
if (file == NULL)
return 1;
char buf[MAXN];
// int buf2[val];
node *first = NULL, *last = NULL;
while (fgets (buf, MAXN, file)) {
node *head = malloc (sizeof(node));
if (head == NULL) {
perror ("malloc-node");
return 1;
}
buf[strcspn(buf, "\n")] = 0;
strcpy (head->name, buf);
head->next = NULL;
if (!last)
first = last = head;
else {
last->next = head;
last = head;
}
}
if (file != stdin)
fclose(file);
node *ptr = first;
while (ptr != NULL) {
node *node_t = ptr;
printf ("%s\n", ptr->name);
ptr = ptr->next;
free (node_t);
}
return 0;
}
I don't where or how to edit my code for it to do what I want it to.
input:
Code:
Martha 12
Bill 33
Max 78
Jonathan 12
Luke 10
Billy 16
Robert 21
Susan 25
Nathan 20
Sarah 22