Jump to content
  • Advertisement
Sign in to follow this  
Kingerthethird

Reading from File to String

This topic is 3042 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[0], 20 );
        fstrScoresFile.ignore( 1 );
        fstrScoresFile >> intScores;
        fstrScoresFile.ignore( 1 );
    }

Thanks in advance.

Share this post


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

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

At this point, strPlayers 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[0], 20 );
std::getline( fstrScoresFile, strPlayers /*, ';'*/ ); // optional delimiter parameter

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

fstrScoresFile >> intScores;
fstrScoresFile.ignore( 1 );
}







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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!