jdoe jdoe - 1 year ago 82
C Question

sscanf for formatting string from file

As part of a homework assignment I need to load a file with data in the following format:

R1 Fre 17/07/2015 18.00 FCN - SDR 0 - 2 3.211
R1 Lor 18/07/2015 16.00 FCM - VFF 2 - 0 7.232

For doing so I used fgets to store the string in a temporary string and after that sscanf to format the string while iterating through the file line by line.

while(fgets(temp, MAX_LINE_SIZE, input_file)!= NULL) {
" %*s %3s %d / %d / %d %s %3s - %3s %d - %d %6s",

..... And so on ....

Current output is:

Weekday: Fre18.00FCNSDR3.211
Day: 17
Month: 7
Year: 2015
Start: 18.00FCNSDR3.211
Home team: FCNSDR3.211
Away team: SDR3.211
Score: 0 - 2
Viewers: 3.211

Expected output is:

Weekday: Fre
Day: 17
Month: 7
Year: 2015
Start: 18.00
Home team: FCN
Away team: SDR
Score: 0 - 2
Viewers: 3.211

The strings with %s placeholder in sscanf seems to putting themselves together for some reason.

All help is much appreciated.

Answer Source

Are you sure you're storing strings like Fre in a 4-byte character array?

%3s actually reads in 4 bytes. F, r, e, and \0. If you use an array too small then you overwrite the \0, causing the string to include whatever comes next in memory (in this case, more strings).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download