【发布时间】:2015-07-13 05:06:30
【问题描述】:
我是一名尝试学习 C++ 的初学者程序员。我正在尝试从文件中读取以下信息:
Dean DeFino 88 98 99
萨莉·约翰逊 78 89 82
比尔·本尼 75 79 81
托马斯·比洛斯 78 84 89
但是,我得到以下输出,但我不知道为什么:
迪恩·德菲诺 88 98 99
0 0 0
萨莉·约翰逊 78 89 82
0 0 0
代码如下:
#include <fstream>
#include <iostream>
#include <iomanip>
using namespace std;
const int NAMESIZE = 15;
const int MAXRECORDS = 50;
struct Grades // declares a structure
{
char name[NAMESIZE + 1];
int test1;
int test2;
int final;
};
typedef Grades gradeType[MAXRECORDS];
// This makes gradeType a data type
// that holds MAXRECORDS
// Grades structures.
void readIt(ifstream&, gradeType, const int);
int main()
{
ifstream indata;
indata.open("graderoll.dat");
int numRecord = 4;
gradeType studentRecord;
if(!indata)
{
cout << "Error opening file. \n";
cout << "It may not exist where indicated" << endl;
return 1;
}
readIt(indata, studentRecord, MAXRECORDS);
// output the information
for (int count = 0; count < numRecord; count++)
{
cout << studentRecord[count].name << setw(10)
<< studentRecord[count].test1
<< setw(10) << studentRecord[count].test2;
cout << setw(10) << studentRecord[count].final << endl;
}
return 0;
}
void readIt(ifstream& inData, gradeType gradeRec, const int max)
{
int total = 0;
inData.get(gradeRec[total].name, NAMESIZE);
while (inData)
{
inData >> gradeRec[total].test1;
inData >> gradeRec[total].test2;
inData >> gradeRec[total].final;
total++;
inData.clear();
inData.get(gradeRec[total].name, NAMESIZE);
}
}
有什么建议可以帮助我解决这个问题吗?
【问题讨论】:
-
对不起,这对我没有帮助。我不相信我的问题与
eof相关 -
文件是在linux还是windows上创建的?你运行的是linux还是windows?
-
@benjy-kessler 该文件是在 Windows 中创建的
-
@benjy-kessler,我使用的是 Mac OS 终端,但我已经在 Windows 中尝试过,得到了同样的结果
标签: c++ file fileoutputstream