std::string strPlayers[10];
for( int i = 0; i < 10; i++ )
{
fstrScoresFile.get( &strPlayers[0], 20 );
fstrScoresFile.ignore( 1 );
fstrScoresFile >> intScores;
fstrScoresFile.ignore( 1 );
}
Reading from File to String
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.
Thanks in advance.
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:
Try that. See also std::getline and istream::getline.
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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement