fscanf()filter
我有一个包含以下格式数据的文件:
名称WeekDay月份日,年份StartHour:StartMin距离小时:分钟:秒
示例:John Mon 2011年9月5日09:18 5830 0:26:37
我想将其扫描成结构:
typedef struct { char name[20]; char week_day[3]; char month[10]; int day; int year; int startHour; int startMin; int distance; int hour; int min; int sec; } List;
我用fscanf():
List listarray[100]; for(int i = 0; ch = fgetc(file) != 'EOF'; ch = fgetc(file), i++){ if(ch != '\0'){ fscanf(file, "%s %s %s %d %d %d %d %d %d %d %d", &listarray[i].name...etc) } }
我的问题是我想过滤掉输入字符串中的噪音,即:
月份日* , *年< – 逗号在所有条目中都是一致的。 我只想要char数组中的月份,即int中的那一天。
时间戳:
startHour:startmin和hour:min:sec < – 这里我想过滤掉冒号。
我是否需要先将其放入字符串然后进行拆分,还是可以在fscanf中处理它?
更新:
好吧,我一直试图让它现在起作用,但我根本不能。 我真的不知道问题是什么。
#include /* Struct to hold data for each runners entry */ typedef struct { char name[21]; char week_day[4]; char month[11]; int date, year, start_hour, start_min, distance, end_hour, end_min, end_sec; } runnerData; int main (int argc, const char * argv[]) { FILE *dataFile = fopen("/Users/dennisnielsen/Documents/Development/C/Afleveringer/Eksamen/Eksamen/runs.txt", "r"); char ch; int i, lines = 0; //Load file if(!dataFile) printf("\nError: Could not open file!"); //Load data into struct. ch = getc(dataFile); //Find the total ammount of lines //To find size of struct array while(ch != EOF){ if(ch == '\n') lines++; ch = getc(dataFile); } //Allocate memory runnerData *list = malloc(sizeof(runnerData) * lines); //Load data into struct for(i = 0; i < lines; i++){ fscanf(dataFile, "%s %s %s %d, %d %d:%d %d %d:%d:%d %[\n]", list[i].name, list[i].week_day, list[i].month, list[i].date, list[i].year, list[i].start_hour, list[i].start_min, list[i].distance, list[i].end_hour, list[i].end_min, list[i].end_sec); printf("\n#%d:%s", i, list[i].name); } fclose(dataFile); return 0; }
我被告知“在fscanf()中只有字符串不需要&在他们面前;” 但无论是否使用&符号,我都尝试过无效。
将“noise”放在格式字符串中。
您也可以限制字符串的大小。
并摆脱&
为arrays。
并测试scanf
的返回值!
// John Mon September 5, 2011 09:18 5830 0:26:37 if (scanf("%19s%2s%9s%d,%d%d:%d%d%d:%d:%d", ...) != 11) /* error */; // ^^^ error: not enough space
注意week_day
有2个字符的空间和零终止符。
您可以将此噪声放在scanf
格式字符串中。
另请注意,对于日期/时间字符串,您可以使用strptime
。 它与scanf
完成相同的工作,但专注于日期/时间。 你可以使用%Y
, %M
……和其他。