Casz146 Casz146 - 3 months ago 11
C Question

Reading lines from CSV file and separating into values (sscanf SIGSEGV)

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.

Answer

The arguments to your sscanf are incorrect, its should be:

sscanf(str[i], "%19[^,], %f", names[i], &grades[i]);

names[i] is a char array, so you should not pass its address, but the address of its first element, which is either &names[i][0] or simply names[i].

Conversely, grades[i] is a float. You must pass its address as &grades[i] or possibly grades + i, but it is less readable.

And you should check the return value to verify in the input string was correctly converted.

Also remove the extra ; at the end of the for block.

Comments