2012-05-01 39 views
1
//Student file 
#include <iostream> 
#include <fstream> 
#include <string> 
#include <iomanip> 
using namespace std; 

#include "student.h" 
#define cap 100 
void main() 
{  string s; 
    class student student[cap],l; 
    int i; 
    fstream f; 

    i=0; 
    cout << "Enter the file name: "; //Display to enter the file name 
    cin >>s; 


    f.open(s.data(),ios::in); 
    if(!f.is_open()) 
     cout << "could not open file"; 
    while(i<cap && !f.eof()) 
    {  cout << "good"; 
     student[i].get(f); 

//Display if okay 
     if(f.good()) 
     { 
      i++; 
      student[i].put(cout); 
      cout << i; 
     } 
    } 
     f.close(); 

} 
class student 
{ 
    public: 
     student(); //Constructor without parameters 
     student(int,string,string,int,float); //Constructor with parameters 
     ~student(); //Deconstructors 
     bool get(istream &); //Input 
     void put(ostream &); //Output 
     int read_array(string,int); 
    private: 
     int id,age; 
     float gpa; 
     string last,first; 
}; 

student::student() 
{ 
    id = 0; 
    first = "null"; 
    last = "null"; 
    age = 0; 
    gpa = 0.0; 
} 
bool student::get(istream &in) 
{ 

    in >> id >> first >> last >> age >> gpa; 
    return(in.good()); 
} 
void student::put(ostream &out) 
{ 
    out << id << first << last << age << gpa; 
} 

当我运行它它显示了构造函数值的重叠和从应该进入数组并显示它们的文件中的数据。我不确定是否正确地将数据放入类数组。从一个文件中读取数据到一个类的数组

+1

'void main()'? '_ಠhttp://www2.research.att.com/~bs/bs_faq2.html#void-main – chris

+1

['while(!f.eof())'](http://coderscentral.blogspot.com/2011/ 03 /读files.html)? –

回答

1

这里有一个问题:

if (f.good()) 
{ 
    // student[i] has just been read from the file. 
    i++;     // Increment counter. 
    student[i].put(cout); // Print whatever was in the next element. 
    cout << i; 
} 

,计数器增加第一,所以student[i]指元素刚才更新一前一后。

+0

哇,谢谢我没有意识到它会这样做的阵列。它确实有道理。谢谢,我很感激! – MIkey27