I have been working on a program that wants to read 10 lines from a csv file and separate the name and the grade. I have used the documentation provided here Reading values from CSV file into variables
Unfortunately, my code throws a SIGSEGV
when coming to the line with the sscanf
statement. I have tried to remove the ,
between %[^,]
and %f
, after which it works but only gets the names, not the grades, which defeats the purpose.
#include <stdio.h>
#include <stdlib.h>
int main() {
char str[10][30], names[10][20];
FILE *fp;
int i;
float grades[10];
fp = fopen("names.txt", "rt");
for (i = 0; i < 10; i++) {
fgets(str[i], 30, fp);
sscanf(str[i], "%[^,], %f", &names[i], grades[i]);
printf("%s ", names[i]);
printf("%f ", grades[i]);
};
}
This is the content of the csv file:
Bob,8
Carla,7
Jack,5
Julie,3
Goncalo,9
Vera,6
Jesse,8
James,8
Francis,10
Monica,6
Thank you for your help, if you need any other information please don't hesitate to ask.