我有这种格式的数据文件:fscanf()函数过滤
名称星期月日,年StartHour:StartMin距离时:分:秒
例子: 约翰星期一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和时:分:秒< - 在这里我想筛选出结肠。
我需要先将它放入一个字符串中,然后做一些拆分,或者我可以在fscanf中处理它吗?
更新:
好吧,SA我一直试图让这个现在的工作,但我根本做不到。我从字面上不知道问题是什么。
#include <stdio.h>
/*
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()函数他们面前&;”但我尝试了无论与否都无济于事。
只有数组(字符串)在scanf调用中不需要'&'; 'int'变量可以:'scanf(...,chararray,&integer)'。在计算行数后,您需要将文件重置为开始(或者,只读一次,并根据需要继续重新分配);提示:使用'rewind'。最后一件事:不要忘记“释放”你分配的内存。最后一件事情(lol):提高编译器的警告级别,并且介意警告**。 – pmg