I'm trying to make a program that reads a csv file that looks like this:
name,hp,damage
duck,20,5
cat,30,10
giraffe,100,20
And I want to print the above csv file like this:
name:duck hp:20 damage:5
name:cat hp:30 damage:10
name:giraffe hp:100 damage:20
The requirement is that the header part of the csv file (name,hp,damage) should be stored into an array called 'header' and when printing the csv file the array 'header' must be used.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char name[1000];
int hp;
int damage;
} Monster;
typedef struct {
char header1[4];
char header2[2];
char header3[6];
} Header;
int main()
{
FILE* fp = fopen("entityData.csv", "r");
if (!fp) {
printf("Error opening file\n");
return 1;
}
Monster monsters[100];
int num_records = 0;
char line[100];
Header headerList[20];
fgets(headerList, sizeof(headerList), fp);
char *hd1, *hd2, *hd3;
hd1 = strtok(headerList, ",");
strncpy(monsters[num_records].name, hd1, 20);
hd2 = strtok(NULL, ",");
hd3 = strtok(NULL, "\n");
while (fgets(line, sizeof(line), fp))
{
char* token = strtok(line, ",");
strncpy(monsters[num_records].name, token, 20);
token = strtok(NULL, ",");
monsters[num_records].hp = atoi(token);
token = strtok(NULL, ",");
monsters[num_records].damage = atoi(token);
num_records++;
}
for (int i = 0; i < num_records; i++) {
printf("name:%s hp:%d damage:%d\n",
monsters[i].name, monsters[i].hp, monsters[i].damage);
}
fclose(fp);
return 0;
}
Here is my code so far. I believe that I was able to get each header values into hd1, hd2, and hd3, but I'm not sure how those can be put into an array and used later. I also know that the print part is wrong right now, but I wrote it like that just to test if the values of each headers are printing well.
Also, the original csv file is in Korean, but I translated them into English for simplicity. So the array sizes might not match what I'm trying to achieve.
Any help would be greatly appreciated!