The code at the bottom is a program to update a txt file with high scores. If I continually update with a new highest or lowest score, there doesn't seem to be any problems. If I enter a number to be inserted between two others, I get unexpected results.
For example, if I enter scores 100,12,7,55, the txt reads:
If I enter scores 100,12,7,5,55, I get:
If I enter scores 4,5,66,100, exit the program, reopen program and enter 100,200, I get:
1 2 3 4 5 6 7
|
200
100
66
100
5
4
|
If I open the txt, delete everything, press enter 10 times, close and save txt, open program and enter scores 100,12,7,55, I get:
Full code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
|
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
fstream scoreWriter( "highscores.txt", ios::in | ios::out );
if( ! scoreWriter.is_open() ){ cout << "error, file not open"; return 0; }
int newScore = 0;
int curScore = 0;
cout << "Enter new high score: ";
cin >> newScore;
while( newScore != 0 )
{
scoreWriter.seekg( ios_base::beg );
streampos preCurScorePos = scoreWriter.tellg();
while( scoreWriter >> curScore )
{
if( curScore < newScore )
{
break;
}
else
{
preCurScorePos = scoreWriter.tellg();
}
}
if( scoreWriter.fail() && !scoreWriter.eof() )
{
cout << "\nFail err, not caused by eof."; return 0;
}
if( scoreWriter.eof() ) { scoreWriter.clear() ;}
vector<int> lesserScores;
scoreWriter.seekg( preCurScorePos );
while( scoreWriter >> curScore )
{
lesserScores.push_back( curScore );
}
if( !scoreWriter.eof() ){cout << "\nErr, this should be eof"; return 0; }
scoreWriter.clear();
scoreWriter.seekp( preCurScorePos );
if( preCurScorePos != 0 ){ scoreWriter << endl; }
scoreWriter << newScore << endl;
for( vector<int>::iterator itr = lesserScores.begin(),
end = lesserScores.end(); itr != end; itr++ )
{
scoreWriter << *itr << endl;
}
cout << "Enter new high score, or 0 to exit: ";
cin >> newScore;
}
return 0;
}
|