クラスオブジェクトのメンバーにファイルを読み込めません。それは、ファイルを読むことができないと言います。クラスオブジェクトへのファイルの読み込み
これが私のクラスである:
const int SIZE_OF = 5;
class Student
{
public:
Student();
Student(const Student &);
Student(string, int, int, int, int, int);
friend std::istream& operator >> (std::istream& in, Student& S);
void display();
private:
string lastName;
int grades[SIZE_OF];
};
関数を定義するために、私のクラスオブジェクトに関連付けられたCPPファイル:
#include "Student.h"
Student::Student()
{
int i;
string lastName = "default";
for (i = 0; i < 5; i++)
{
grades[i] = 0;
}
}
Student::Student(const Student & S)
{
int i;
lastName = S.lastName;
for (i = 0; i < 5; i++)
{
grades[i] = S.grades[i];
}
}
Student::Student(string S, int a, int b, int c, int d, int e)
{
lastName = S;
grades[0] = a;
grades[1] = b;
grades[2] = c;
grades[3] = d;
grades[4] = e;
}
std::istream& operator >> (std::istream& in, Student& S)
{
char dummy;
in >> S.lastName >> S.grades[0]
>> dummy >> S.grades[1]
>> dummy >> S.grades[2]
>> dummy >> S.grades[3]
>> dummy >> S.grades[4];
return in;
}
void Student::display()
{
int i;
int sum = 0;
double average;
cout << "Last Name: " << lastName << endl;
cout << "Grades: " << endl;
for (i = 0; i < 5; i++)
{
cout << grades[i] << endl;
}
for (i = 0; i < 5; i++)
{
sum = sum + grades[i];
}
average = sum/5;
cout << "Average: " << average;
}
そして、私はテストするために、これまで持って最終的には、主な機能ファイルを開いてクラス内のさまざまな変数に読み込みます。
void main()
{
fstream File;
string FileName = "ProgramSixData.txt";
bool FoundFile;
string Line;
Student testStudent;
do {
File.open(FileName, ios_base::in | ios_base::out);
FoundFile = File.is_open();
if (!FoundFile)
{
cout << "Could not open file named " << FileName << endl;
File.open(FileName, ios_base::out); // try to create it
FoundFile = File.is_open();
if (!FoundFile)
{
cout << "Could not create file named " << FileName << endl;
exit(0);
}
else;
}
else;
} while (!FoundFile);
do {
File >> testStudent;
if (File.fail())
{
cout << "Read Failed" << endl;
cout << "Bye" << endl;
exit(0);
}
else;
testStudent.display();
} while (!File.eof());
cout << "Bye" << endl;
File.close();
}
私はから読んでいたテキストドキュメントでは、次のされています
私は学生のクラスの特定のオブジェクトに名前と関連付けられている5つの段階のそれぞれを保存するにはどうすればよいGeorge
75,85,95,100,44
Peter
100,100,100,100,100
Frank
44,55,66,77,88
Alfred
99,88,77,66,55
?
正確なエラーは何ですか? –
正確に動作していないのは何ですか?また、ifステートメントは必ずしもelseを必要としません。 –
私の主なステートメントでは、File.fail()に遭遇した場合に「読み込みに失敗しました」と読み上げています。 –