I have a line in a file like this: "33 sun 15:00 FCM - SIF 3 - 0". I need to extract all of the data. I have this code so far, which makes a little error when extracting the strings "sun", "FCM" and "SIF". It makes "sun" into "sunFCMSIM", "FCM" into "FCMSIF" while "SIF" is correct.
You can just make the input file from multiple lines like the one above. So how do I make sure that this information is extracted correct?
#include <stdio.h>
#include <stdlib.h>
#define LINEBUFFERSIZE 50
#define TEAMNAMELENGTH 3
#define WEEKDAYLENGTH 3
void __construct(char fileName[FILENAME_MAX]) {
FILE *inputFile;
char buffer[LINEBUFFERSIZE];
// Open input file
inputFile = fopen(fileName, "r");
// Read all matches and create
while(fgets(buffer, LINEBUFFERSIZE, inputFile) != NULL){
int round, hour, minute, homeGoals, outGoals;
char outTeam[TEAMNAMELENGTH], homeTeam[TEAMNAMELENGTH], weekday[WEEKDAYLENGTH];
fscanf(inputFile, "%d %3s %2d:%2d %3s - %3s", &round, weekday, &hour, &minute, homeTeam, outTeam);
printf("Round: %d\n", round);
printf("%s %开发者_Python百科02d:%02d\n", weekday, hour, minute);
//printf("%s - %s\n", homeTeam, outTeam);
}
fclose(inputFile);
}
int main() {
/*char inputFile[FILENAME_MAX];
printf("Enter input file> "); scanf("%s", &inputFile);*/
__construct("superliga-2009-2010");
return 0;
}
According to the documentation for fscanf
, the s
conversion specifier:
Matches a sequence of non-white-space characters; the next pointer must be a pointer to character array that is long enough to hold the input sequence and the terminating null character ('\0'), which is added automatically.
Your buffers are not large enough to accommodate the NULL terminator. If you fix that, for example by declaring outTeam
, homeTeam
and weekday
as follows:
char outTeam[TEAMNAMELENGTH + 1], homeTeam[TEAMNAMELENGTH + 1], weekday[WEEKDAYLENGTH + 1];
Your code works as expected.
精彩评论