【发布时间】:2015-07-17 14:45:55
【问题描述】:
当我按“2”读取文件时,虽然我的语法正确,但无法读取文件中的数据。为什么我的程序无法读取数据?顺序访问文件和随机访问文件有什么区别,为什么首选随机访问文件?
void EnterRecord();
void ShowRecord();
using namespace std;
class student
{
int rollno;
string name;
int marks;
public:
void SetData();
void DisplayData();
void MainMenu();
};
void student:: MainMenu()
{
cout<<" "<<endl;
cout<<"press 1 to enter record"<<endl;
cout<<"press 2 to show record"<<endl;
}
void student::SetData()
{
cout<<"enter roll no of student"<<endl;
cin>>rollno;
cout<<"enter name of student"<<endl;
cin>>name;
cout<<"enter marks of student"<<endl;
cin>>marks;
}
void student::DisplayData()
{
cout<<rollno<<setw(10)<<setw(10)<<marks<<endl;
}
int main()
{
student s1;
int choice;
repeat:
s1.MainMenu();
cout<<"enter ur choice ::"<<endl;
cin>>choice;
switch(choice)
{
case 1:
EnterRecord();
break;
case 2:
ShowRecord();
break;
}
return 0;
}
void EnterRecord()
{
ofstream myfile;
myfile.open("student3.txt",ios::app);
int choice=1;
while(choice==1)
{
student s1;
s1.SetData();
myfile.write((char*)&s1,sizeof(student));
cout<<"press 1 to enter record again"<<endl;
cin>>choice;
if(choice!=1)
{
system("cls");
s1.MainMenu();
}
}
myfile.close();
}
void ShowRecord()
{
student s2;
ifstream myfile;
myfile.open("student3.txt");
myfile.seekg(0);
while(myfile.eof())
{
myfile.read((char*)&s2,sizeof(student));
}
s2.DisplayData();
}
【问题讨论】:
-
您的
case表达式不正确。它们应该是'1'和'2',而不是简单的1和2。您还应该开始检查您调用的函数返回的错误。另见Why is iostream::eof inside a loop condition considered wrong? -
请不要随便在句末加上完全不同的问题...
-
寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定的问题或错误以及重现它所需的最短代码在问题本身。没有明确问题陈述的问题对其他读者没有用
标签: c++ file-handling