3

我发布了以下代码,我正在从输入文件中读取信息——将信息存储在结构中——然后写入输出文件。我知道该eof功能不安全,因此必须使用该getline功能检查是否检测到文件结尾;但是,在这个特定的代码中,我无法使用该getline函数,因此最终依赖于该eof函数。因此,您能否建议该函数的替代方案,或者让我知道在尝试初始化结构数组时eof如何使用该函数。getline我使用了两个星号来表示我想在哪里使用该getline功能。

#include <iostream>
#include <fstream>

using namespace std;
//student structure
struct student
{
  char name[30];
  char course[15];
  int age;
  float GPA;
};

ifstream inFile;
ofstream outFile;

student getData();
void writeData(student writeStudent);
void openFile();

int main (void)
{
  const int noOfStudents = 3; // Total no of students
  openFile(); // opening input and output files

  student students[noOfStudents]; // array of students

  // Reading the data from the file and populating the array
  for(int i = 0; i < noOfStudents; i++)
  {
        if (!inFile.eof()) // ** This where I am trying to use a getline function.
            students[i] = getData();
        else
            break ;
  }


  for(int i = 0; i < noOfStudents; i++)
    writeData(students[i]);

  // Closing the input and output files
  inFile.close ( ) ;
  outFile.close ( ) ;

}

void openFile()
{
  inFile.open("input.txt", ios::in);
  inFile.seekg(0L, ios::beg);
  outFile.open("output.txt", ios::out | ios::app);
  outFile.seekp(0L, ios::end);

  if(!inFile || !outFile)
  {
    cout << "Error in opening the file" << endl;
    exit(1);
  }

}

student getData()
 {
  student tempStudent;
  // temp variables for reading the data from file

  char tempAge[2];
  char tempGPA[5];

  // Reading a line from the file and assigning to the variables
  inFile.getline(tempStudent.name, '\n');
  inFile.getline(tempStudent.course, '\n');
  inFile.getline(tempAge, '\n');

  tempStudent.age = atoi(tempAge);

  inFile.getline(tempGPA, '\n');
  tempStudent.GPA = atof(tempGPA);
  // Returning the tempStudent structure
  return tempStudent;
 }

void writeData(student writeStudent)
 {
  outFile << writeStudent.name << endl;
  outFile << writeStudent.course << endl;
  outFile << writeStudent.age << endl;
  outFile << writeStudent.GPA << endl;
 }
4

2 回答 2

3

你想operator>>为你的学生类型写一个。就像是:

std::istream& operator>>(std::istream& in, student& s) {
  in >> s.age; // etc.
  return in;
}

然后允许您编写:

int studentNo = 0;
students[maxStudents];
while (studentNo < maxStudents && (in >> students[studentNo]))
  ++studentNo;
于 2012-08-01T19:36:34.720 回答
0

为什么不这样写?

代替

inFile.getline(tempStudent.name, '\n');
inFile.getline(tempStudent.course, '\n');
inFile.getline(tempAge, '\n');

你可以

while(inFile.getline(tempStudent.name, '\n'))
{
    inFile.getline(tempStudent.course, '\n');
    inFile.getline(tempAge, '\n');
    //do stuffs
}
于 2012-08-01T19:35:53.897 回答