从文本文件加载时遇到麻烦
Having trouble loading from a text file C++
我在从文本文件加载到值时遇到麻烦。我希望它从文本文件加载,但数字保持不变。
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()
中看不到结果。
相关文章:
- 查找奇数平方和时遇到麻烦
- CSUF EPP - 你有什么想法(在添加到链接列表末尾时遇到麻烦)
- MySQL 从注入过渡到参数化时遇到麻烦
- C++击球平均值程序使用输入/输出文件打印名称,平均值,最高/最低平均值时遇到麻烦
- 以分类方式插入节点时遇到麻烦
- 在此任务上遇到麻烦,我们需要使用指针和数组来找到文本文件中某些数字的平均值,中值和模式
- 我在DFS搜索(树)代码中遇到麻烦.我如何打破递归
- 我在处理字符时遇到麻烦
- 在我的代码覆盖本身时遇到麻烦,我不确定为什么
- C++处理文件,在制作程序时遇到麻烦
- 在客户端/服务器计算器C 方面遇到麻烦
- 从一个字符串中获取 2-5 个连续的单词短语,我得到了 2 个工作,但在做 3 个时遇到麻烦
- boost :: phoenix ::功能遇到麻烦
- 在具有模板成员功能的模板类方面遇到麻烦
- 通过模板参数遇到麻烦
- 快速排序在C++,遇到麻烦
- 计算字符时遇到麻烦
- 在C++中摸索多个排他性组合时遇到麻烦
- 编译phash程序时遇到麻烦
- 在 Linux 上为 OpenGL 4.2 设置开发环境(查找 gl.h 时遇到麻烦)