Dean Hampson Dean Hampson - 10 days ago 4
C++ Question

Loading information from file C++

I have a program that loads information from a file into player class variables. All works fine except for the last variable playerdamage..

void Player::loadplayer(std::string name)
{
std::ifstream UserFile;
UserFile.open(name + ".txt");

if (UserFile.is_open())
{
while (UserFile.good())
{
getline(UserFile, playername, ';');
getline(UserFile, playerpass, ';');
UserFile >> playercash;
UserFile >> playercoords;
UserFile >> playerdamage;
}
}
UserFile.close();
}


Here are the file contents (with playerdamage being the last one):

Allura;Password123;5.00;0.0;10.00


But if I log in and type 'stats':

enter image description here

It all loads correctly except for the damage.

Answer

What appens if you use only get line ?

        getline(UserFile, playername, ';');
        getline(UserFile, playerpass, ';');
        getline(UserFile, playercash, ';');
        getline(UserFile, playercoords, ';');
        getline(UserFile, playerdamage);

if you want integer or double value convert your data after getline call :

To convert string to int :

atoi( str.c_str() ) // C++ 98

std::stoi( str ) // C++ 11

To convert string to double:

atof( str.c_str() ) // C++ 98

std::stod( str ) // C++ 11

so you get something like this:

        string playercoordsString;
        getline(UserFile, playercoordsString, ';');
        playercoords = std::stod(playercoordsString);
Comments