gpt4 book ai didi

c++ - 从文件 C++ 加载信息

转载 作者:行者123 更新时间:2023-11-27 22:48:18 24 4
gpt4 key购买 nike

我有一个程序可以将文件中的信息加载到播放器类变量中。除了最后一个变量 playerdamage..

void Player::loadplayer(std::string name)
{
std::ifstream UserFile;
UserFile.open(name + ".txt");

if (UserFile.is_open())
{
while (UserFile.good())
{
getline(UserFile, playername, ';');
getline(UserFile, playerpass, ';');
UserFile >> playercash;
UserFile >> playercoords;
UserFile >> playerdamage;
}
}
UserFile.close();
}

这是文件内容(playerdamage 是最后一个):

Allura;Password123;5.00;0.0;10.00

但是如果我登录并输入“stats”:

enter image description here

除了损坏之外,它都正确加载。

最佳答案

问题是您用“;”分隔值>> 运算符处理文件中的连续字符,并且不知道分号是您的分隔符。

解决这个问题最简单和最快的方法是在每次调用后从文件中跳过一个字符。所以你会得到这样的代码:

UserFile >> playercash;
UserFile.ignore(1);
UserFile >> playercoords;
UserFile.ignore(1);
UserFile >> playerdamage;

通过这种方式,所有转换仍然由流本身处理 - 这很好,对开发人员来说编码更少。

另一种方法需要更多工作。基本上根据文档,ifstream operator>> 按描述工作(简而言之)

Extracts and parses characters sequentially from the stream to interpret them as the representation of a value of the proper type, which is stored as the value of val.

您的示例中的变量是未知类型,如果它们是用您自己的类型指定的,那么您可以重载 ifstream operator>>

关于c++ - 从文件 C++ 加载信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40741943/

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