Reading from File to String

Started by
2 comments, last by Zahlman 14 years, 2 months ago
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.
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.
SWEET MERCIFUL GODS, THANK YOU!

I did it with the copying to char array first, and it's working fine. Thank you.
What are the actual file contents?

This topic is closed to new replies.

Advertisement