2012-06-29 25 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)) 
{ 
}