我无法从文本文件加载到某个值。我希望它从文本文件加载,但数字保持不变。
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 ++,所以我有点困惑。我正在运行Codeblocks和&#39; Data.txt&#39;是在&#39; bin&#39;文件夹中。
编辑:
改变主要。
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();
}
答案 0 :(得分:1)
如果你遵循πάνταῥεῖ的建议,不确定你做错了什么,但这有效:
#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;
}
答案 1 :(得分:0)
更改您的功能签名以通过引用获取参数:
bool load_from_file(string filename, Player& P) {
// ^
原样,您的功能只会修改Player
参数的副本,而main()
中的结果不会显示。