I've written a code, wherein i'm trying to get all the rows which start from "A". I have A, A12 etc in my csv file and i want to read all those rows. But i got the following error. Not sure where i went wrong. Kindly help.
CSV file
M,2,lion
A,1,tiger
B,2,cat
A1,7,dog
C,3,man
A2,9,mouse
A23,9,pouch
myfile.c
#include <stdio.h>
#include <stdlib.h>
#define NUMLETTERS 100
typedef struct {
char letter[100];
int number;
char ani[100];
} record_t;
int main(void) {
FILE *fp;
record_t records[NUMLETTERS];
size_t count = 0;
fp = fopen("letters.csv", "r");
if (fp == NULL) {
fprintf(stderr, "Error reading file\n");
return 1;
}
while (fscanf(fp, " %s,%d,%s", records[count].letter, &records[count].number, records[count].ani) == 3) {
count++;
}
for (size_t i = 0; i < count; i++) {
if(records[i].letter== "A"){
printf("%s,%d,%s\n", records[i].letter, records[i].number,records[i].number);
}
}
fclose(fp);
return 0;
}
Error
myfile.c:29:16: warning: format ‘%s’ expects argument of type ‘char *’, but argument 4 has type ‘int’ [-Wformat=]
printf("%s,%d,%s\n", records[i].letter, records[i].number,records[i].number);
Since you search fields that start with
A, you only need to compare the first letter ofletter, so your line 28 becomes:And your compiler told you that you try to display an integer as a string, it's because you have a typo in line 29:
numberinstead ofani, the line should be:It comes from your
scanfcall: inscanf,%swill read until in find a space (space or tab or line feed). You have to tell to scanf to stop too readletterafter the first comma found. To do this, replace%swith%99[^,]. More explanations here: Scanf guide.So your reading loop should looks like: