I am trying to read from a file that has comma seperated values like so (5th field should only have r/b/n and 6th field is y/n:
531,A,10,10,b,n,96.00,100.00
531,B,15,15,b,n,144.00,0.00
531,C,20,20,b,n,192.00,0.00
533,A,11,11,r,n,123.20,100.00
533,B,22,22,r,n,246.40,0.00
I have the following fscanf code block to parse the file by line and store values in an array which I alter/output later.
while(fscanf(data, "%4[0-9],%[A-Z],%3[0-9],%3[0-9],[prb],[yn],%d,%d\n", &house[i], room[i], &length[i], &width[i], paintcode[i], ceilingcode[i], &cost[i], &setupcost[i]) != EOF) {
printf("%d,%c,%d,%d,%c,%c,%.2lf,%.2lf\n", &house[i], room[i], &length[i], &width[i], paintcode[i], ceilingcode[i], &cost[i], &setupcost[i]);
i++;
}
Unfortunately, I am getting a Segmentation fault and it occurs at this line. I have altered and tested it for about an hour and I am pretty sure I have it right, unless I am missing something. Any help would be appreciated, the full main function is pasted below.
main() {
FILE *data;
int house[200];
char room[200];
int length[200];
int width[200];
char paintcode[200];
char ceilingcode[200];
double cost[200];
double setupcost[200];
char line;
int MAX_BUFF = 200;
char x[200];
double price[100];
int i = 0, num_records = 0;
data = fopen("quotes.data","r");
if(data == NULL){
printf("Error: file can't be open..\n");
} else {
while(fscanf(data, "%4[0-9],%[A-Z],%3[0-9],%3[0-9],[prb],[yn],%d,%d\n", &house[i], room[i], &length[i], &width[i], paintcode[i], ceilingcode[i], &cost[i], &setupcost[i]) != EOF) {
printf("%d,%c,%d,%d,%c,%c,%.2lf,%.2lf\n", &house[i], room[i], &length[i], &width[i], paintcode[i], ceilingcode[i], &cost[i], &setupcost[i]);
i++;
}
fclose(data);
There are quite a few issues here.
For a start, the
scanffamily will only returnEOFif reading failed without getting any input values. If you successfully get some but not all, you will get a count of the number successfully scanned (including the case where you got them all).You also need to pass the address of the variables you want to populate, which you haven’t done for all of them.
In addition, a format specifier like
%4[0-9]will read characters, not a single integer so it would require a character buffer, not an address of an integer as you have. If you want an integer populated, you need to use something like%4d.On the
%[A-Z]front, these actually create a null-terminated string so you need to allow space for that.Also ensure you can read the the floating point values at the end of the line rather than integers, and you’re missing some
%format characters.And lastly,
printfrequires addresses only for string arguments.The following program shows this in action in simplified form (no arrays) with your input file: