我有這種格式的數據文件: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