I am trying to parse some simply formatted text and create a simple data structure of text/numeric records using numeric and short string values. I have debugged and located the problem; it's down to sscanf() not reading the values into my variables using a specific format string (other format strings in the program work well). I have created a simple text file to see what's happening.
Code is as follows:
char *idNumber = (char *)malloc(sizeof (char*));
char *partNumber = (char *)malloc(sizeof (char*));
int amountItems = 0;
double unitPrice = 0;
char *line1 = "Govan, Guthrie (N210) AX299 x 6 $149.94";
char *line2 = "Mustaine, Dave (N106) AX350N x 2 $63.98";
char *line3 = "Van Halen, Edward (N1402) AV2814 x 10 $34.90";
sscanf(line1, "%*s, %*s (%s) %s x %d $%lf", idNumber, partNumber,
&amountItems, &unitPrice);
printf("%s, %s, %d, %f\n", idNumber, partNumber, amountItems, unitPrice);
sscanf(line2, "%*s, %*s (%s) %s x %d $%lf", idNumber, partNumber,
&amountItems, &unitPrice);
printf("%s, %s, %d, %lf\n", idNumber, partNumber, amountItems, unitPrice);
sscanf(line3, "%*s, %*s (%s) %s x %d $%lf", idNumber, partNumber,
&amountItems, &unitPrice);
printf("%s, %s, %d, %lf\n", idNumber, partNumber, amountItems, unitPrice);
I am interested in the following fields, with the rest being ignored. For instance, in record:
"Govan, Guthrie (N210) AX299 x 6 $149.94"
I want N210, AX299, 6, and 149.94 in my variables, in that order.
Result is as follows:
andrew@levin-Inspiron-3650:~/Desktop/schoolwork/project2$ ./a.out
, , 0, 0.000000
, , 0, 0.000000
, , 0, 0.000000
Expected output is:
N210, AX299, 6, 149.94
N106, AX350N, 2, 63.98
N1402, AV2814, 10, 34.90
Please share help!
This is not code directly from my program but a "helper" file I created on the side just to debug this one issue very simply without having to invoke the entire application!
The following similar code worked well for a different format: Record being:
N210 AX299 6 24.99
in following code:
struct record *current = malloc(sizeof(struct record *));
current->idNumber = (char *)malloc(sizeof (char *) * 8);
current->partNumber = (char *)malloc(sizeof (char *) * 10);
sscanf(line, "%s %s %d %lf", current->idNumber, current->partNumber,
&(current->amountItems), &(current->unitPrice));
I do not expect this code to be a wealth of C beauty, I am a Java developer this is a C project for community college. But can you help me debug this one sscanf problem.
Thank you!