C++文件数据插入

该博客介绍了如何使用C++编程向已排序的Scores.txt文件中插入新的成绩记录,详细说明了在VS2013和Code::Blocks两个开发环境下的操作结果。
摘要由CSDN通过智能技术生成

目的:向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
  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值