将txt文件加载到C ++类的数组中

时间:2014-11-14 00:14:47

标签: c++ arrays file class

我试图从文本文件中加载一些值并输出它。当它输出时,我只收到txt文件的最后一行....为什么它只读取txt文件的最后一行?我创建了一个类数组,并将每个数据加载到文件中,我想输出它。任何建议都有助于谢谢 主文件:

#include <iostream>
#include "membertype.h"
#include <string>
#include <iomanip>
#include <fstream>
#include <cstdlib>

memberType members[500];
int getMembersData();
void printMembersData();

int main(int argc, char** argv)
{
    memberType();
    getMembersData();
    printMembersData();

    return 0;
}

int getMembersData()
{
    cout << fixed << setprecision(2);
    double spent;
    int bbought;
    string fname, lname,id;
    ifstream infile;
    infile.open("project8.txt");
    if(!infile)
    {
        cout << "unable to open input file. "<< endl;
        return 1;
    }

    infile>>id>>fname>>lname>>bbought>>spent;
    while ( !infile.eof())
    {
        for(int j=0;j<5;j++)
        {
            members[j].setMemberInfo(id,fname,lname,bbought,spent);
        }

        infile>>id>>fname>>lname>>bbought>>spent;
    }
    infile.close();

    return EXIT_SUCCESS;
}

void printMembersData()
{
    for(int i=0;i<5;i++)
        members[i].printInfo();
}

实施档案:

#include<iostream>
#include<string>
#include"membertype.h"
using namespace std;

memberType::memberType()
{
    string memberID ="non";
    string firstName="emp";
    string lastName="bloop";
    int booksPurchased=0;
    double amountSpent=0;
}

void memberType::setMemberInfo(string ID, string fName, string lName, int bPurchased, double amount)
{
    memberID = ID;
    firstName = fName;
    lastName = lName;
    booksPurchased = bPurchased;
    amountSpent = amount;
}

void memberType::printInfo()
{
    cout<<memberID<<firstName<<lastName<<booksPurchased<<amountSpent<<endl;
}

0 个答案:

没有答案