【发布时间】:2012-08-01 19:32:00
【问题描述】:
我发布了以下代码,我正在从输入文件中读取信息——将信息存储在结构中——然后写入输出文件。我知道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;
}
【问题讨论】:
-
这是一道作业题吗?只是问,因为它没有作业标签,而且代码看起来很学术。这个问题本身很好。
-
不,这不是作业问题。我只是在练习结构以及如何将它们写入文件。