所以我试图从我写的二进制文件中读取一个结构,但似乎有问题。这是我的主要内容:
//Fraction structure
struct Fraction
{
int num, den;
};
int main()
{
int menu_selection;
char slash;
fstream datafile; //creates file object
Fraction* f; //creates pointer for dam
//menu to the user
menu_selection = main_menu();
bool condition = true;
while (condition)
{
switch(menu_selection)
{
case 1: //adds a new Fraction structure to binary file
f = new Fraction; //dynamically allocating memory
cout << "Enter fraction to add: "; //adds fraction to file
cin >> f->num >> slash >> f->den;//stores input
datafile.open("fractions.dat",ios:: out | ios:: app | ios::binary); //creates file
datafile.write(reinterpret_cast<char *>(f),sizeof(Fraction));//stores fraction to file
datafile.close();
menu_selection = main_menu();
break;
case 2:
menu_selection = main_menu();
break;
case 3: //displays the contents of the file to user
datafile.open("fractions.dat", ios::in | ios::binary);
while(!datafile.eof())
{
datafile.read(reinterpret_cast<char *>(f),sizeof(f));
cout << f->num << "/" << f->den << " ";
}
datafile.close();
menu_selection = main_menu();
break;
case 4:
menu_selection = main_menu();
break;
case 5:
menu_selection = main_menu();
break;
case 6: condition = false;
return 0;
break;
default: cout << endl << "That is an invalid option. Please try again." << endl; //default option
break;
}
}
delete f;
}
当用户输入 1 时,我为结构 Fraction 动态分配内存并将其写入二进制文件。我使用 ios::app 是因为我想在再次调用文件时添加到文件中。写入或读取功能有什么问题吗?每当我按原样运行程序时,如果我输入一个分数,例如 1/5,它会显示 1/5 5/5 5/5,但是如果我输入两个分数,例如 1/5 和 2/6,它会显示2/6 6/6 6/6。