2012-06-29 38 views
0

我創建了加載形式的一個非常基本的地圖文件中的函數:SDL fscanf函數問題

1:1 2:1 1:1 2:2 2:2 2:2 ... 
................... 2:1 1:1 

然而,在使用fscanf當讀取文件,我得到了一些非常奇怪的行爲。

看着FILE變量我已經設置爲讀取地圖,FILE的'stream'的base元素似乎已經完美地讀取了該文件。然而,FILE的'流'的_ptr缺少第一個數字,而最後一個。所以它讀作:

:1 2:1 1:1 2:2 2:2 2:2 ... 
................... 2:1 1: 

並且正在產生一個錯誤。

這裏是我的功能:

/** 
* loads a map 
*/ 
bool Map::LoadMap(char* tFile) 
{ 
    FILE* FileHandle = fopen(tFile, "r");   // opens map file for reading 

    if (FileHandle == NULL)       // returns if the map file does not exist 
     return false; 

    for(int Y = 0; Y < MAP_HEIGHT; Y++)    // iterates through each row 
    { 
     for(int X = 0; X < MAP_WIDTH; X++)   // iterates through each column 
     { 
      Node tNode;       // temp node to put in the map matrix 

      int  tTypeID  = 0; 
      int  tNodeCost = 0; 

      fscanf(FileHandle, "%d:%d", tTypeID, tNodeCost); 

      tNode.SetPosition(X, Y); 
      tNode.SetType(tTypeID); 
      tNode.SetNodeCost(tNodeCost); 

      mMap[X][Y]  = tNode;    // inserts temp node into list 
     } 
     fscanf(FileHandle, "\n"); 
    } 

    fclose(FileHandle); 

    return true; 
} 

爲什麼發生這種情況?

回答

3

您需要的變量的地址傳遞給fscanf()

fscanf(FileHandle, "%d:%d", &tTypeID, &tNodeCost); 

推薦檢查fscanf()的返回值,以確保成功:

// fscanf() returns the number of assignments made or EOF. 
if (2 == fscanf(FileHandle, "%d:%d", &tTypeID, &tNodeCost)) 
{ 
}