gpt4 book ai didi

C++:读取和排序二进制文件

转载 作者:行者123 更新时间:2023-11-30 01:58:46 24 4
gpt4 key购买 nike

这几天我一直在挠头,把这个作业搁置了几天,但现在我蹲下来尝试去做,我却一无所获。我需要做 4 件事。

1) 读取二进制文件并将数据放入数组

2)按照考试成绩从低到高排序

3) 平均得分并输出

4) 用排序后的数据创建一个新的二进制文件

这是二进制数据文件看起来未排序的样子

一个。史密斯 89

T。菲利普 95

S。长76

我可能可以排序,因为我认为我知道如何使用并行数组和索引排序来解决这个问题,但是读取二进制文件并将该数据放入数组对我来说非常困惑,因为我的书却没有。真的解释得不是很好。

到目前为止,这是我的初步代码,实际上并没有做太多事情:

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <Windows.h>
using namespace std;



int get_int(int default_value);
int average(int x, int y, int z);

int main()

{


char filename[MAX_PATH + 1];
int n = 0;
char name[3];
int grade[3];
int recsize = sizeof(name) + sizeof(int);
cout << "Enter directory and file name of the binary file you want to open: ";
cin.getline(filename, MAX_PATH);

// Open file for binary write.
fstream fbin(filename, ios::binary | ios::in);
if (!fbin) {
cout << "Could not open " << filename << endl;
system("PAUSE");
return -1;
}

}

很抱歉这样的新手问题。

编辑:抱歉,前面提到的数据文件应该是它应该的样子,二进制文件是一个 .dat,用记事本打开时里面有这个:

A.Smith ÌÌÌÌÌÌÌÌÌÌÌÌY T. Phillip ÌÌÌÌÌÌÌÌÌ_ S. Long ip ÌÌÌÌÌÌÌÌL J. White p ÌÌÌÌÌÌÌÌd

最佳答案

在 C++ 中读取文件很简单:

从文件创建一个流[以便从流中读取](你有文件流[输入/输出],字符串流......)

    ifstream fin;  //creates a fileinput stream

fin.open(fname.c_str(),ifstream::binary); // this opens the file in binary mod


void readFile(string fname)
{
ifstream fin;
fin.open(fname.c_str()); //opens that file;
if(!fin)
cout<<"err";
string line;
while(getline(fin,line)) //gets a line from stream and put it in line (string)
{
cout<<line<<endl;
//reading every line
//process for you need.
...
}
fin.close();
}

正如您指定的那样,该文件只是一个文本文件,因此您可以处理每一行并执行任何您想做的事情。

关于C++:读取和排序二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16879321/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com