我正在尝试写入文本文件,但在我的代码执行后,我只能看到写入文件的时间和日期,而不是我需要写入文件的实际数据。
奇怪的是,当我运行程序时,我可以看到存储在内存中的数据,直到我关闭Windows控制台,但它没有将数据存储到文件中。
我有使用ifstream的代码并且在最后关闭,所以我不确定是否可能保持文件打开。此外,当我写入文件时,我的程序写入光标的最后位置而不是文件的末尾。这是我写入文件的代码。
void createPerson (Person persons[], int* count) {
char fullName[100];
char personAddress[200];
int Marks1;
int Marks2;
int Marks3;
int Marks4;
int Marks5;
int personNumber;
string personGender;
ofstream outfile("testFile.txt", std::ios_base::app);
if(outfile.fail()){
cerr << "File cannot be opened" << endl;
}
cout<<"Enter the person's number: "<<endl;
cin>>personNumber;
cout <<"Enter the person's Full name: "<<endl;
cin.ignore();
cin.getline(fullName,50);
cout<<"Enter the score for Marks1: "<<endl;
cin>>Marks1;
cout<<"Enter the score for Marks2: "<<endl;
cin>>Marks2;
cout<<"Enter the score for Marks3: "<<endl;
cin>>Marks3;
cout<<"Enter the score for Marks4: "<<endl;
cin>>Marks4;
cout<<"Enter the score for Marks5: "<<endl;
cin>>Marks5;
cout<<"Enter the person's address: "<<endl;
cin.ignore();
cin.getline(personAddress,50);
cout<<"Enter the person's sex: "<<endl;
cin>>personGender;
persons[*count] = person(personNumber,fullName,
Marks1,Marks2, Marks3, Marks4, Marks5,
personAddress, personGender);
(*count)++;
outfile << persons[*count].getpersonNumber()<<":";
outfile << persons[*count].getpersonName()<<":";
outfile << persons[*count].getMarks1()<<":";
outfile << persons[*count].getMarks2()<<":";
outfile << persons[*count].getMarks3()<<":";
outfile << persons[*count].getMarks4()<<":";
outfile << persons[*count].getMarks5()<<":\n";
outfile << persons[*count].getPersonAddress()<<":";
outfile << persons[*count].getPersonGender();
outfile.close();
cout << persons[*count].getPersonName();
}