从文本文件加载时遇到麻烦

Having trouble loading from a text file C++

本文关键字:遇到 麻烦 加载 文本 文件      更新时间:2023-10-16

我在从文本文件加载到值时遇到麻烦。我希望它从文本文件加载,但数字保持不变。

Data.txt

7
7

文件的第1行是Health,我正在尝试加载。

Player.h

#ifndef PLAYER_H
#define PLAYER_H
class Player
{
    public:
        int Health;
        int MaxHealth;
        Player() { this->Health = 9; this->MaxHealth = 9; }
};
#endif // PLAYER_H

和main.cpp

#include <iostream>
#include "Player.h"
#include <fstream>
using namespace std;
void save_to_file(string filename, Player P)
{
    ofstream f( filename.c_str() );
    f << P.Health << endl;
    f << P.MaxHealth << endl;
}
bool load_from_file(string filename, Player P)
{
    ifstream f( filename.c_str() );
    f >> P.Health;
    f >> P.MaxHealth;
    return f.good();
}
int main()
{
    Player P;
    load_from_file("Data.txt", P);
    cout << P.Health << endl;
    return 0;
}

谢谢!我刚学了c++,所以有点困惑。我正在运行代码块,'Data.txt'在'bin'文件夹中。

编辑:

主要变化。

bool load_from_file(string filename, Player& P)
{
    ifstream f( filename.c_str() );
    f >> P.Health;
    f >> P.MaxHealth;
    if(f.good()){
        cout << "Sucess!" << endl;
    } else {
        cout << "Failure" << endl;
    }
    return f.good();    
}

不知道你做错了什么如果你遵循π α ντα ρ ε ω的建议,但这是有效的:

#include <iostream>
#include <fstream>
using namespace std;
class Player {
public:
  int Health, MaxHealth;
};
void save_to_file(string filename, const Player& P)
{
    ofstream f( filename.c_str() );
    f << P.Health << endl;
    f << P.MaxHealth << endl;
}
bool load_from_file(string filename, Player& P) {
  ifstream f( filename.c_str() );
  f >> P.Health;
  f >> P.MaxHealth;
  if(f.good()){
    cout << "Success!" << endl;
  }
  else {
    cout << "Failure" << endl;
  }
  return f.good();
}
int main() {
  Player P;
  load_from_file("Data.txt", P);
  cout << P.Health << endl;
  return 0;
}

修改你的函数签名,通过引用来接受参数:

bool load_from_file(string filename, Player& P) {
                                        // ^

实际上,您的函数只修改了Player参数的副本,并且在main()中看不到结果。