Sign in to follow this  

Reading from File to String

This topic is 2853 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm having a problem doing a highscore system for one of my games. The problem is in the small segment of code below. When I do the loop once, everything works fine. If I do the loop more than once, all the the strPlayers come back empty. fstrScoresFile is a fstream object. I'm having a real problem getting this to work, and its one of the last touches I need, any help would be appreciated. I'm beating my head against the wall. Windows 7, Codeblocks with the Mingw compiler, if it matters.
    std::string strPlayers[10];
    for( int i = 0; i < 10; i++ )
    {
        fstrScoresFile.get( &strPlayers[i][0], 20 );
        fstrScoresFile.ignore( 1 );
        fstrScoresFile >> intScores[i];
        fstrScoresFile.ignore( 1 );
    }

Thanks in advance.

Share this post


Link to post
Share on other sites
You've got a potential buffer overrun:

fstrScoresFile.get( &strPlayers[i][0], 20 );

At this point, strPlayers[i] is empty, or points to a string with enough space for a single character ('\0'). Besides, changing the internals of std::string directly is asking for trouble. Try reserving memory first, or use an alternate method:


std::string strPlayers[10];
for( int i = 0; i < 10; i++ )
{
// fstrScoresFile.get( &strPlayers[i][0], 20 );
std::getline( fstrScoresFile, strPlayers[i] /*, ';'*/ ); // optional delimiter parameter

// or
char temp[20] = {};
fstrScoresFile.get( temp, 20 );
strPlayers[i] = std::string( temp );

fstrScoresFile >> intScores[i];
fstrScoresFile.ignore( 1 );
}







Try that. See also std::getline and istream::getline.

Share this post


Link to post
Share on other sites

This topic is 2853 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this