Question:
I am trying to read each line from a file (.txt file below) while storing its contents in the appropriate variables. The problem occurs when compiling. I am told there is a segmentation fault but am not sure why this occurring.
tester1.txt file(disregard spaces)
1/12/04 Jones, John $31.11
12/22/03 Dickinson, Tony $5.04
12/15/03 Lee, Jerry $21.12
12/19/03 Kahn, Chris $83.15
1/31/04 Bills, Mike $32.00
1/15/04 Lake, Jeff $6.66
Code:
int main() {
int month, day, year;
float money;
char *lastname, *firstname;
static const char filename[] = "tester1.txt";
FILE *file = fopen (filename, "r");
if (file != NULL) {
char line [128]; /* or other suitable maximum line size */
while (fgets(line, sizeof line, file ) != NULL) {
sscanf(line,"%d/%d/%d %s, %s $%f", &month, &day, &year, lastname,
firstname, &money);
printf("%d/%d/%d %s, %s $%.2f\n", month, day, year, lastname,
firstname, money );
// printf("valid: %s\n", line);
// fputs ( line, stdout ); /* write the line */
}
fclose (file);
}
else {
perror (filename); /* why didn't the file open? */
}
return 0;
}
You need to allocate memory for the strings, you can't just declare them as pointers:
char lastname[256], firstname[256];
Also, in the scanf
you can specify anything but comma (and space), otherwise the comma is also read as a part of the string:
sscanf(line,"%d/%d/%d %[^, ], %s $%f", &month, &day, &year,
lastname, firstname, &money);
First you have allocate memory for the strings, like perreal said. Then you have to change the sscanf
char str_money[100];
sscanf(line,"%d/%d/%d %s%s%s",
&month, &day, &year, lastname, firstname, str_money);
Because if you scanf %f, you will not get that tidy float number. And scanf %s only stop at space
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.