C++,关于从txt文件中读取数据到电脑上的问题。急。

2025-03-28 21:49:43
推荐回答(1个)
回答1:

自定义一个结构类型,用其变量存放每个人的信息。实用的当然是链表,但略复杂些;作为作业,又有200个人的上限,那用结构体数组就可以了。举例代码如下:

//#include "stdafx.h"//If the vc++6.0, with this line.
#include "stdlib.h"
#include 
#include 
using namespace std;
struct STU{
    char name[15];
    int ser_n;
    int Chin;
    int Math;
    int Engl;
};
int main(int argc,char *argv[]){
    STU stu[200];
    int i,j;
    ifstream filein("aaa.txt");
    if(!filein){
        cout << "Open the file failure...\n";
        exit(0);
    }
    i=0;
    while(filein >> stu[i].name >> stu[i].ser_n >> stu[i].Chin >> stu[i].Math >> stu[i].Engl)
        i++;
    filein.close();
    //到这里就把文件数据全读进数组stu里了,以后排序、求平均值或干其他事都可以了
    cout << endl;
    return 0;
}