目的:向Scores.txt文件(已排好序的成绩列表),插入一条新的成绩。
代码:
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
fstream file("Scores.txt", ios::in | ios::out);
if (!file.is_open())
{
cout << "Could not open file!" << endl;
return 0;
}
int new_score;
cout << "Enter a new high score: " << endl;
cin >> new_score;
streampos pre_score_pos = file.tellg();
int cur_score;
while (file >> cur_score)
{
if (cur_score<new_score)
{
break;
}
pre_score_pos = file.tellg();
}
if (file.fail() && !file.eof())
{
cout << "Bad score/read--exiting";
return 0;
}
file.clear();
file.seekg(pre_score_pos);
vector<int> scores;
while (file >> cur_score)
{
scores.push_back(cur_score);
}
if (!file.eof())
{
cout << "Bad score/rea