I have this Homework assignment where I have to read lines one by one from a file and then parse it.
The text file looks like this: The number of lines varies from file to file.
NGM8 Nguyen, Michael; 25 30 45 20
SIS7 Sinn, Scott; 30 25 20 21
SMJ0 Smith, Jacob; 27 25 24 26
.....etc
where the first column is the ID of the person, the next is the name, and the four numbers at the end are sales figures per week for 4 weeks.
My segment of code to read this file is:
char id[5];
char name[50];
int i1, i2, i3, i4;
fgets(temp, sizeof(temp), infile); // where infile is the file pointer passed to this function from main. The file opened successfully in main.
sscanf(temp, "%s %s; %d %d %d %d", id, name, &i1, &i2, &i3, &i4);
printf("id=%s name=%s sales: %d %d %d %d\n", id, name, i1, i2, i3, i4);
Here was the screen output based on printf above:
id=2685531 name=Johnson, sales: 0 16777216 0 7557016
Can someone help me with this? What should the sscanf statement look like to correctly read in values for these variables?
Thanks.
As I mentioned in a comment, the %s
specifier reads until whitespace or the end of data. So if you want to read a string token that's delimited by a ';'
character, you'll need to use something else. Fortunately, there's the %[
specifier which lets you provide a set of characters to accept or - more often useful - a set of characters to stop the match.
Try the following:
sscanf(temp, "%s %[^;]; %d %d %d %d", id, name, &i1, &i2, &i3, &i4);
// ^^^^^
The second token (which corresponds to the name) will read characters until it hits a semicolon (and will leave the semicolon in the input stream - therefore the literal ;
following it to consume that character).
FWIW, I'm not a huge fan of parsing data with scanf()
functions - it can be tricky to handle errors, corner cases, and making sure that you don't exceed buffer boundaries for strings. But they should often be fine for homework assignments or when you really have a fixed format input file.