Fat problem with Ifstream on a member string!

Dec 23, 2013 at 11:37am
Im about to program a game with a CPlayer class.
It looks like this:
1
2
3
4
5
6
7
8
9
10
11
12
#include <string>
#include <fstream>
#include <iostream>

using namespace std;

 class CPlayer{
friend class CGame;
private:
string m_name;
//and the rest is irrelevant
}

Now, ive got another class named CGame, with the member function
 
loadplayer()

So:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class CGame{
private:
ofstream m_out;
ifstream m_in;

public:
void loadplayer(CPlayer* player){
m_in.open("savegame.sav", ios::binary);
m_in.read((char*) &(player->m_name), sizeof(player->m_name);
m_in.close();
cout << player -> m_name;
}
//there is also a saveplayer func which only writes the name into a file with the same way as above.

//the rest is irrelevant
}


and now, when i call the loadplayer func he sends instead of the name simply the char 'G'
I dunno why especially this letter or why itndoesnt show the right string.
Pls help me im about to get dizzy.
Dec 23, 2013 at 12:02pm
Dec 23, 2013 at 6:47pm
You've made some odd assumptions about what's relevant and what's not. Context can make quite a difference in these matters.

For example we don't see where m_name is being initialised, so when you do
m_in.read((char*) &(player->m_name), sizeof(player->m_name);
What exactly is the size of m_name? How many characters will be read from the file?
In that case, why not something like getline(m_in, player->m_name);?
Dec 23, 2013 at 6:48pm
BTW, you're missing a closing parenthesis in line 9
Topic archived. No new replies allowed.