gpt4 book ai didi

c++ - 无法从文件中正确读取整数 C++

转载 作者:行者123 更新时间:2023-11-30 01:43:08 25 4
gpt4 key购买 nike

我正在用 C++ 制作平铺引擎/游戏。我苦苦挣扎的是,我不太清楚如何从文件中加载和操作整数数据。

这是 mapfile.map:

[jbs@dmb-gaming-laptop ~]$ cat cpp/adventures_of_ironville/mapfile.map 
0000001111101111
0000111000020000
1100000000000000
0100200000111000
0110000000111200
0010002200111120
2010002220111111
0010022200001111
0000001111101111
0000111000020000
1100000000000000
0100200000111000
0110000000111200
0010002200111120
2010002220111111
0010022200001111
[jbs@dmb-gaming-laptop ~]$

这是我游戏中的关卡。现在,对于我正在努力处理的代码:

bool World::loadLevelFromDisk(std::string pathToMapFile)
{
//Our file object
std::ifstream file(pathToMapFile);

//Store contents of file
char tempData;

if (!file.is_open()) {
//Error...
return false;
} else { //File is ready to use
while (!file.eof())
{
//Grab one character.
tempData = file.get();

//Convert that character
//to ascii integer.
int data = tempData - 48;

//std::vector used elsewhere,
//which must take an int.
currentLevel.push_back(data);

//Why does this output a bunch of -38's?
//expected output is to be identical to the
//mapfile.map.
std::cout << data;
}
}
}

最后一个 std::cout 的输出:

0000001111101111-380000111000020000-381100000000000000-380100200000111000-380110000000111200-380010002200111120-382010002220111111-380010022200001111-380000001111101111-380000111000020000-381100000000000000-380100200000111000-380110000000111200-380010002200111120-382010002220111111-380010022200001111-38-49

如何从文件中读取整数数据??我花了很多时间尝试不同的解决方案,从字符串流到 boost::lexical_cast,但我还没有找到有效的答案。这是我得到的最接近预期结果的结果,即将文件读取为整数,以便可以在其他地方进行操作。非常感谢所有帮助!

最佳答案

-38其实就是line feed(\n字符)你读10(换行的ascii码,然后计算10 - 48)

只需在您的代码中通过以下修改省略它们:

...
tempData = file.get();
if ( tempData == '\n' || tempData =='\r' ) continue;
...

\r 字符仅适用于 Windows,但格外小心也无妨。

另一种方法是简单地忽略任何不是数字的东西,在这种情况下,条件是:

if ( tempData < '0' || tempData > '9' ) continue;

关于c++ - 无法从文件中正确读取整数 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38276183/

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