gpt4 book ai didi

c++ - 在这种情况下避免使用eof

转载 作者:太空狗 更新时间:2023-10-29 21:26:23 26 4
gpt4 key购买 nike

我已经发布了以下代码,我从输入文件中读取信息——将信息存储在结构中——然后写入输出文件。我知道 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;
}

最佳答案

您想为您的学生类型编写一个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;

关于c++ - 在这种情况下避免使用eof,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11766234/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com