我正在用scanf
讀取文件。每行只有一個數據字段,所以我有一個do while while循環。基本上我所做的是,閱讀第一個構建根的信息(我使用它來構建BST)。但是,當進入內心的時候。閱讀奇怪的事情。讀取並創建正確的所有數據,但對於循環的每次迭代,調用兩次相同的方法來讀取文件,而現在我不知道發生了什麼。用scanf和while while循環讀取文件
comp_node_ptr read_competitor_node(int id, FILE * competitor_filename){
int scan_status;
int feet;
double inches;
competitor_node * tmp_node;
tmp_node = calloc(1, sizeof(tmp_node));
scan_status = fscanf(competitor_filename, "%[^\n]\n", tmp_node -> name);
if(scan_status == EOF){
printf("End Of File. \n");
free(tmp_node);
return NULL;
}
tmp_node -> id = id;
fscanf(competitor_filename, "%[^\n]\n", tmp_node -> addres);
fscanf(competitor_filename, "%[^\n]\n", tmp_node -> phone_number);
fscanf(competitor_filename, "%d %lf", &feet, &inches);
tmp_node -> cucumber = convertToInches(feet, inches);
fscanf(competitor_filename, "%d %lf", &feet, &inches);
tmp_node ->carrot = convertToInches(feet, inches);
fscanf(competitor_filename, "%d %lf", &feet, &inches);
tmp_node -> bean = convertToInches(feet, inches);
printNode(tmp_node);
return tmp_node;
}
root = read_competitor_node(id, competitor_table_file);
do{
id++;
tmp_node = read_competitor_node(id, competitor_table_file);
add_competitor(root, tmp_node);
}while(tmp_node != NULL);
並打印以下數據:
Margaret Mouse 1 Southern 9565 1 ft -0.500000 in 2 ft -3.200001 in 1 ft -4.500000 in -134217728 ft 0.000000 in
2 1 ft -4.500000 in 1 ft -4.500000 in 1 ft -4.500000 in 0 ft 0.000000 in
Bert Hill 3 Central 2010 1 ft -7.200001 in 1 ft -8.200001 in 2 ft -11.700001 in 156587349 ft -4.000000 in
4 � 27263573 ft -4.000000 in 27263573 ft -4.000000 in 27263573 ft -4.000000 in 0 ft 0.000000 in
Donald Duck 5 Marine 1234567 2 ft -0.400000 in 2 ft -4.500000 in 1 ft -6.200001 in 145402538 ft -8.000000 in
6 � 27263570 ft -8.000000 in 27263570 ft -8.000000 in 27263570 ft -8.000000 in -67108864 ft 0.000000 in
End Of File.
2,4和6,我不知道從哪裏而來。 1,3和5是我正在閱讀的文件中的正確數據,但是他們來自哪個文件?
的結構數據如下:
typedef struct competitor_status {
int id;
char name[MAX_TEXT_LENGTH];
char addres[MAX_TEXT_LENGTH];
char phone_number[MAX_TEXT_LENGTH];
float cucumber;
float carrot;
float bean;
struct competitor_status * left; /* links to teams with more or same points */
struct competitor_status * right; /* links to teams with less points */
} competitor_node;
typedef competitor_node * comp_node_ptr;
爲什麼你使用'calloc'來初始化'tmp_node'如果它不是一個數組?請改用'malloc' –
確保分配給該變量的所有空間都設置爲零,以前刪除 –
之前的那些輸出,看起來您的代碼看起來像是一個BufferOverFlow,或者指針分配不當。 –