Reputation: 23
So I'm having some issues with fscanf and using a delimiter.
#include <stdio.h>
typedef struct
{ short int custID;
char name[25];
char address1[30];
char address2[30];
short int numBikes;
char bikeType;
char cusRisk;
} CUSTOMER;
int main(void){
short int i = 0,j,ID;
double total = 0;
char exit;
char c;
FILE *input;
FILE *output;
input = fopen("input.txt","r");
output = fopen("output.txt","w");
// Allow up to 25 orders to be placed at once
CUSTOMER order[25];
system("clear");
// THIS IS WHERE I'M HAVING ISSUES
while((fscanf(input, "%hd %25[^;]; %30[^;]; %30[^;]; %hd %c %c",&order[i].custID, order[i].name, order[i].address1, order[i].address2, &order[i].numBikes, &order[i].bikeType, &order[i].cusRisk) == 7)){
printf("Name: %s\n",order[i].name);
printf("Address1: %s\n",order[i].address1);
printf("Address2: %s\n",order[i].address2);
printf("NumBikes: %hd\n",order[i].numBikes);
printf("BikeType: %c\n",order[i].bikeType);
printf("cusRisk: %c\n",order[i].cusRisk);
i++;
}
fclose(input);
return 0;
}
This is a sample of the input.txt
1111 John Smith ;320 E. Oak ;Warrensburg MO 64093 ;2 M Y
My problem is that it is storing the name, address1, and address2 all in the name variable. Then it stores address1 and address2 in the address1 variable. Finally it stores address2 in address2 like would be expected. So the output would be something like this:
Name: John Smith 320 E. Oak Warrensburg MO 64093
Address1: 320 E. Oak Warrensburg MO 64093
Address2: Warrensburg MO 64093
I can't seem to figure out why it is doing this. I expected it to stop at the first delimiter store it in name then read the ;
and stop there for name variable but apparently that's not true. Any help on why it would be doing this would be appreciated.
Upvotes: 2
Views: 567
Reputation: 41852
The problem is that you are reading 25 chars into name
, and 30 into address1
and address2
. Since this is the size of these buffers, there is no room left for a terminating null. When you print out the name
field, printing does not stop at the end of that buffer and it prints the following two.
Try adding 1 to the size of these buffers. The scanf
function will automatically insert a null character after reading the specified number of characters.
Upvotes: 2