C++如何用void调用ifstream?

C ++ How to call ifstream with void?

总结:

1 - 带变量的结构

2——给变量赋值

3 - void 在文件中保存变量

4 - 将值更改为变量

5 - void load values into variables <--- 这里我有问题

6 - 我显示值

我的问题是:我正在创建一个系统,用于使用代码块在 C++ 中保存和加载 "games"。一个简单的代码用于创建有问题的系统,但也用于存储在 .txt 或 .dat 中的结构(几乎所有 int)中的变量的值。

#include<iostream>
#include<fstream>

using namespace std;

///GAME VAR
struct NewGame{
float tipo;
float health;
};

///SAVE_LOAD
void saveGame( NewGame G );
void loadGame( NewGame ( & G ) );

int main(){

///STRUCT
NewGame G;

///VALUE ASIGN (TEST)
cout << "Ingrese tipo [1] [2] [3]" << endl;
cin >> G.tipo;
cout << "Ingrese vida"<<endl;
cin >> G.health;

///SAVE STRUCT
    saveGame( G );

///CHANGE VALUES
G.health = 0;
G.tipo = 0;

///LOAD STRUCT <-----HERE'S THE PROBLEM
    loadGame( G );

///TEST VALUES
cout << "HEALTH: " << G.health << endl;
cout << "TYPE: " << G.tipo << endl;


return 0;
}

///SAVE
void saveGame( NewGame G){

ofstream s;
    s.open("save.txt");
    s << G.health << endl;
    s << G.tipo << endl;
    s.close();

};

///LOAD
void loadGame( NewGame ( & G ) ){

ifstream l;
    l.open("save.txt");
    l >> G.health;
    l >> G.tipo;
    l.close();

};

我已经试了好几种方法了,binary和txt的问题总是一样,保存数据,加载新游戏后测试数值,变量的数值一直没有已恢复。

因为您将 G 的副本传递给 loadgame() 函数。尝试 void loadGame( NewGame& G ) 而不是。

所以,我打算继续回答我自己,只是 up-vote 当前答案,但我认为我需要解决当前答案没有的问题。

问题根本不在 ifstream 上。看一下loadGame()里面的G的值,应该没问题:

///LOAD
void loadGame( NewGame G ){

    ifstream l;
    l.open("save.txt");
    l >> G.health;
    l >> G.tipo;
    l.close();

    // My additions: print the value of the variables stored in G
    std::cout << "Health: " << G.health << "\n";
    std::cout << "Tipo: " << G.tipo << "\n";

}

这应该有正确的值。如果是这样,那么您可以确定 ifstream 工作正常。那不是你的问题。

你的问题是你的参数是passed by value。这意味着 loadGame() 仅使用传递给它的数据副本, 而不是原始数据 。这实际上意味着 main() 无法访问 loadGame().

中的数据

您有两个选择:一个是将您的函数更改为 return a NewGame(根据您的问题我假设这不是一个选项,并且必须 return void 出于某种原因)或者,两个,pass by reference:

///LOAD
void loadGame( NewGame& G ){ // a single & makes all the difference here

    ifstream l;
    l.open("save.txt");
    l >> G.health;
    l >> G.tipo;
    l.close();
}

这将允许您从 main().

访问 G 中的值