如何使用>>将.txt文件加载到对象数组中超载? C ++

时间:2013-10-22 02:45:33

标签: c++ arrays class object

这是我第一次在这个网站上发帖,所以请不要错过任何错误/礼仪搞砸了!

基本上我周三有一个项目(是的,一个班级)。代码用C ++编写,它是一个程序,它从下面列出的.txt文件中获取以下数据成员(在学生类中定义):

class Student
{
public: 
    //other functions such as add/edit/delete, etc... go here
private:
    string firstname;
    string lastname;
    int grade; //1 for Freshman, 2 for Sophmore, 3 for Junior, 4 for Senior
    int student_id;
    double credit_hours; //credit hours taken
    double GPA; //current GPA
};

我还附上了下面的.txt文件。基本上我必须在.txt文件中读入该类类型的数组,即Student类的对象。我们的老师说我们可以假设阵列的最大尺寸是[100]学生。我尝试过readFile()函数的几种变体,但都没有。我知道我必须超载>>运算符与Student类一起工作,但我不知道如何做到这一点。她建议朋友的功能?

这是名为“StudentRecords.txt”的.txt文件,与另一个.cpp文件保存在同一目录中。

Harry
Smith
2
11121321
100
3.8
Mary
Jones
1
43213843
56
3.1
Nicolas
Dodsworth
4
54219473
120
2.3
J.Alfred
Prufrock
4
83746321
122
4.0
T.S.
Eliot
1
99999999
126
4.0
Charlotte
Webb
3
44443333
98
3.8
Don
Juan
1
12345678
56
1.2
John
Smith
2
54234876
66
2.85
Darth
Vader
2
87623450
49
2.55
3
CPO
4
33333333
100
4.0
Emily
Dickinson
3
23456120
110
3.6
James
Buchanan
1
5640012
30
2.23
Carl
Rove
1
12995425
28
1.6
Marie
Curie
4
88888888
96
3.5
Micky
Mouse
2
8222222
64
1.85
James
Madison
3
66633333
88
2.96
Dolly
Madison
3
53423445
84
3.24
Pepe
LePew
1
73737373
42
2.47
Homer
Simpson
4
7223344
105
1.03
Mary
Jones
1
09274726
28
2.92
Bloss
Sims
4
11111111
100
1.2

谢谢你们!我非常感谢你的帮助。我对C ++主要是Python没有很多经验,所以这肯定会帮助我。

编辑:

以下代码。 read函数是最后一个函数:

    #include <iostream>
#include <string>
#include <fstream>

using namespace std;

class stdRecord
{
public:
    string studentID;
    string studentName;
    int courseCode;
    int creditPoint;
};

const int MAXRECORD = 100;

int menu();
void searchStudent(stdRecord[],int);
void showByCourse(stdRecord[],int);
//void showEligible(stdRecord[],int);
void showAll(stdRecord[],int);
void update(stdRecord[],int );
void add(stdRecord[],int *);
void deleteRecord(stdRecord[],int *);
void findCourses(stdRecord [],int );

int main()
{
    stdRecord stdRec[MAXRECORD]={"15000000","Joshua Andrew Smith", 3506, 240,"16666666", "Jack Williams", 3506, 180,"17000010", "Lily Jones", 3639, 110};
    int counter=3;
    int choice;
    do
    {
        choice=menu();
        switch(choice)
        {
            case 0: cout<<"Bye for Now"<<endl;
            break;
            case 1: searchStudent(stdRec,counter);
            break;
            case 2:showByCourse(stdRec,counter);
            break;
            case 3://showEligible(stdRec,counter);
            break;
            case 4:showAll(stdRec,counter);
            break;
            case 5:update(stdRec,counter);
            break;
            case 6:add(stdRec,&counter);
            break;
            case 7:deleteRecord(stdRec,&counter);
            break;
        }
    }while(choice!=0);
    system("pause");
}

int menu()
{
    int choice;
    cout<<"0. Exit"<<endl
    <<"1. Search for a student"<<endl
    <<"2. List students enrolled in a course"<<endl
    <<"3. List students eligible to graduate"<<endl
    <<"4. List all students"<<endl
    <<"5. Update a student record"<<endl
    <<"6. Add a student record"<<endl
    <<"7. Delete a student record"<<endl    
    <<"Your choice ->";
    cin>>choice;
    return choice;
}

void searchStudent(stdRecord stdRec[],int counter)
{
    string ID;
    cout<<"Enter the student ID to search-> ";
    getline(cin,ID);

    for(int i=0;i<counter;i++)
    {
        if(stdRec[i].studentID.compare(ID)==0)
        {
            cout<<"The record with the id is:"<<endl;
            cout<<"StudentID\tStudentName\tCourseCoce\tCreditPoint"<<endl;
            cout<<stdRec[i].studentID<<"\t"<<stdRec[i].studentName<<"\t"<<stdRec[i].courseCode<<"\t"<<stdRec[i].creditPoint<<endl;
            cout<<"Have completed the requested process."<<endl;
            system("pause");
            system("cls");
            return;
        }
    }
    char ch;
    cout<<"Not Found"<<endl;
    cout<<"Do you want search another record(Y/N)";
    cin>>ch;
    ch=tolower(ch);
    if(ch=='y')
    searchStudent(stdRec,counter);
    else
    {
    cout<<"Have completed the requested process."<<endl;
    system("pause");
    system("cls");
    }
}
void findCourses(stdRecord stdRec[],int counter)
{
    int courses[500];
    int coursecount=0;
    cout<<" Enter the course code {";
    bool found;
    for(int i=0;i<counter;i++)
    {
        found=false;
        for(int j=0;j<coursecount;j++)
        {
            if(stdRec[i].courseCode==courses[j])
            {
                found=true;
                break;
            }
        }
    if(!found)
        courses[coursecount++]=stdRec[i].courseCode;
    }
    cout<<" Enter the course code {";
    for(int j=0;j<coursecount-1;j++)
        cout<<courses[j]<<", ";
    cout<<"or "<<courses[coursecount-1]<<"->";
}

void showByCourse(stdRecord stdRec[],int counter)
{
    int courseCode;
    findCourses(stdRec,counter);
    cin>>courseCode;
    cout<<"The student(s) enrolled in the course is(are):"<<endl;
    cout<<"StudentID\tStudentName\tCourseCoce\tCreditPoint"<<endl;
    int studentsCount=0;
    for(int i=0;i<counter;i++)
    {
        if(stdRec[i].courseCode==courseCode)
        {
            cout<<stdRec[i].studentID<<"\t"<<stdRec[i].studentName<<"\t"<<stdRec[i].courseCode<<"\t"<<stdRec[i].creditPoint<<endl;
            studentsCount++;
        }
    }
    cout<<"There is(are) "<<studentsCount<<" student(s) enrolled in the course."<<endl;
    cout<<"Have completed the requested process."<<endl;
    system("pause");
    system("cls");
}


void showEligible(stdRecord stdRec[],int counter)
{
    cout<<"The student(s) eligible to graduate is(are):"<<endl; 
    int studentsCount=0;
    for(int i=0;i<counter;i++)
    {
        if(stdRec[i].creditPoint>=240)
        {
            cout<<stdRec[i].studentID<<"\t"<<stdRec[i].studentName<<"\t"<<stdRec[i].courseCode<<"\t"<<stdRec[i].creditPoint<<endl;
            studentsCount++;
        }
    }
    cout<<"There is(are) "<<studentsCount<<" graduate student(s)."<<endl;
    cout<<"Have completed the requested process."<<endl;
    system("pause");
    system("cls");
}


void showAll(stdRecord stdRec[],int counter)
{
    cout<<"All students are listed below:"<<endl;
    for(int i=0;i<counter;i++)
    {
        cout<<stdRec[i].studentID<<"\t"<<stdRec[i].studentName<<"\t"<<stdRec[i].courseCode<<"\t"<<stdRec[i].creditPoint<<endl;
    }
    cout<<"Have completed the requested process."<<endl;
    system("pause");
    system("cls");
}

void update(stdRecord stdRec[],int counter)
{
    char keepGoing;
    string ID;
    do
    {

        cout<<"Enter the student ID to update-> ";
        getline(cin,ID);
        bool flag=false;
        char choice;
        for(int i=0;i<counter;i++)
        {
            if(stdRec[i].studentID.compare(ID)==0)
            {
                cout<<"The record with the id is:"<<endl;                                         cout<<"StudentID\tStudentName\tCourseCoce\tCreditPoint"<<endl;
                cout<<stdRec[i].studentID<<"\t"<<stdRec[i].studentName<<"\t"<<stdRec[i].courseCode<<"\t"<<stdRec[i].creditPoint<<endl;
                cout<<"Enter y or Y to update the course code, others to keep the original one."<<endl;
                cin>>choice;
                if(choice=='y'||choice=='Y')
                {
                    int courseCode;
                    findCourses(stdRec,counter);
                    cin>>courseCode;
                    stdRec[i].courseCode=courseCode;
                }
                cout<<"Enter y or Y to update the credit";
                cin>>choice;
                if(choice=='y'||choice=='Y')
                {
                    int credits;
                    cout<<"Enter Credit points";
                    cin>>credits;
                    stdRec[i].creditPoint=credits;
                }
                flag=true;
                break;
            }
        }
        if(!flag)
        {
            cout<<"The record with the id "<<ID<<" not Found"<<endl;
        }
            cout<<"Do you want update another record(Y/N)";
            cin>>keepGoing;
            keepGoing=tolower(keepGoing);
    }while(keepGoing=='y');

    cout<<"Have completed the requested process."<<endl;
    system("pause");
    system("cls");
}

void add(stdRecord stdRec[],int *counter)
{
    string studentID;
    string studentName;
    int courseCode;
    int creditPoint;
    cout<<"Enter Student ID :";
    cin>>studentID;
    bool flag=true;
    for(int i=0;i<*counter;i++)
    {
        if(stdRec[i].studentID.compare(studentID)==0)
        {
        flag=false;
        break;
        }
    }
    if(flag)
    {
        stdRec[*counter].studentID=studentID;
        cout<<"Enter Student Name \n";
        cin >> studentName;
        stdRec[*counter].studentName=studentName;
        cout<<"Enter Course Code \n";
        cin >> courseCode;
        stdRec[*counter].courseCode=courseCode;
        cout << "Enter Credit Points \n";
        cin >> creditPoint;
        stdRec[*counter].creditPoint=creditPoint;
    }
    else
    {
        cout<<"Student Id Exists"<<endl;
    }
    cout<<"Have completed the requested process."<<endl;
    system("pause");
    system("cls");
}

void deleteRecord(stdRecord stdRec[],int *counter){}



void readIn(stdRecord stdRec[])
{
    ifstream file("StudentRecords.txt");
    if(file.is_open())
    {
        stdRecord stdRec[MAXRECORD];

        for(int i = 0; i < MAXRECORD; i++)
        {
            file >> stdRec[i];
        }
    }
}

1 个答案:

答案 0 :(得分:1)

我认为这就是你想要的:

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;

class Student {
public:
    //define and/or modify your own constructors here
    Student() {}

    friend istream& operator >>(istream &input, Student& student);
    friend ostream& operator <<(ostream &output, const Student& student);//I gave you this as a BONUS

private:
    string firstname;
    string lastname;
    int grade;
    int student_id;
    double credit_hours;
    double GPA;
};

istream& operator >>(istream &input, Student& student) {
    input   >> student.firstname
            >> student.lastname
            >> student.grade
            >> student.student_id
            >> student.credit_hours
            >> student.GPA;
    return input;
}

ostream& operator <<(ostream &output, const Student& student) {
    output  << student.firstname << " "
            << student.lastname << " "
            << student.grade << " "
            << student.student_id << " "
            << student.credit_hours << " "
            << student.GPA << "\n";
    return output;
}

int main() {
    ifstream ifile;
    ifile.open("StudentRecords.txt", ios::in);

    if (!ifile.is_open()) {
        cerr << "There was an error opening the input file!\n";
        exit(0);
    }

    Student student;

    while(ifile >> student) {
        cout << student;
    }
    return 0;
}

根据您拥有的数据,输出:

James Buchanan 1 5640012 30 2.23
Carl Rove 1 12995425 28 1.6
Marie Curie 4 88888888 96 3.5
Micky Mouse 2 8222222 64 1.85
James Madison 3 66633333 88 2.96
Dolly Madison 3 53423445 84 3.24
Pepe LePew 1 73737373 42 2.47
Homer Simpson 4 7223344 105 1.03
Mary Jones 1 9274726 28 2.92
Bloss Sims 4 11111111 100 1.2

正如所料。

唯一的问题是,此代码适用于一个学生,而不是100个。但是,您可以这样做 - 毕竟一切都在适度。您所要做的就是创建一个Student个对象的数组,对它们进行迭代并为它们分配类似于我的方式。