As I said, you are using saving a memory address to the file. I already explained why that is a wrong approach.
However, there is nothing wrong with saving strings to files and then retrieving them, e.g.
Code:
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <string>
class Member
{
private:
std::fstream file;
std::string user;
public:
void setUser();
std::string getUser() const;
bool saveUser();
bool loadUser();
};
void Member::setUser()
{
std::cout << "Enter user name: ";
std::cin >> user;
if (!std::cin)
{
throw std::runtime_error("Set user failed!!\n");
}
}
std::string Member::getUser() const
{
return user;
}
bool Member::saveUser()
{
bool result = false;
file.open("record.txt", std::fstream::app | std::fstream::out);
if ( !file.is_open()) {
throw std::runtime_error("Couldn't open file\n");
}
file << user << std::endl;
if (file) {
result = true;
}
file.close();
return result;
}
bool Member::loadUser()
{
bool result = false;
file.open("record.txt", std::fstream::in);
if ( !file.is_open())
{
throw std::runtime_error("Couldn't open file\n");
}
file >> user;
if (file)
{
result = true;
}
file.close();
return result;
}
int main()
{
Member member;
member.setUser();
if ( !member.saveUser())
{
std::cerr << "Failed to save the user (broken file) !!\n";
return 0;
}
if ( !member.loadUser())
{
std::cerr << "Failed to load the user (record.txt: no content) !!\n";
return 0;
}
std::cout << "User retrieved from file is " << member.getUser() << std::endl;
return 0;
}
You can see that this at least retrieves something from a file.