gpt4 book ai didi

c++ - SDL fscanf 函数问题

转载 作者:行者123 更新时间:2023-11-28 00:55:56 26 4
gpt4 key购买 nike

我创建了一个函数来加载一个非常基本的 map 文件,格式如下:

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

但是,当使用 fscanf 读取文件时,我遇到了一些非常奇怪的行为。

查看我为读取 map 而设置的 FILE 变量,FILE 的“流”的 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;
}

为什么会这样?

最佳答案

您需要将变量的地址传递给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))
{
}

关于c++ - SDL fscanf 函数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11264744/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com