【发布时间】:2015-08-18 01:12:39
【问题描述】:
运行SaveToFile() 后文件为空。它不会打印任何东西。另外,当我在DisplayFromFile() 中使用while(file.eof() == 0) 而不是while(file.read(...)) 时,它会永远循环。
using namespace std;
void database::SaveToFile()
{
fstream file;
file.open("abc", ios::ate);
for (int i = 0; i < count - 1; i++)
{
file.write((char *) &s[i], sizeof s[i]);
}
file.close();
}
void database::DisplayFromFile()
{
student stud;
fstream file;
file.open("abc", ios::in);
file.seekg(0, ios::beg);
cout << "Rollno\t|\tMarks " << endl;
cout << "------------------------------------" << endl;
while (file.read((char *) &stud, sizeof stud))
{
cout << stud.getrollno() << "\t|\t" << stud.getmarks() << endl;
}
file.close();
}
【问题讨论】:
-
除非你只有普通数据类型,否则你会在读写数据时遇到麻烦(即
std::string或std::vector将是一个问题)。 -
你建议我怎么做?
-
for(int i=0;i<count-1;i++)应该是for(int i=0;i<count;i++)。 -
嘿,成功了!谢谢!