为什么我的程序不从文件中读取数据
why my program does not read the data from file
当我按"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();
}
最大的问题是,您将student
的实例视为单个纯旧数据块(POD),而实际上它不是。它包含一个std::string
的实例,其中包含您不知道的内部数据。第一个也是最明显的是,它包含一个指向字符串数据的指针。当你把它写出来时,你保存的是指针值而不是实际的字符串。当你重新加载它时,它会读取旧的指针值,这个值只有在你是一个非常幸运的小妖精时才有效。
您的函数EnterRecord
和ShowRecord
将需要更新,以便它们序列化student
的每个成员,而不是将其作为单个blob的普通旧数据写出来。下面的内容应该可以让你开始。
保存数据:
myfile << st.rollno;
myfile << st.name;
myfile << st.marks;
加载数据myfile >> st.rollno;
myfile >> st.name;
myfile >> st.marks;
既然你没有提供任何关于文件应该如何布局的信息,那么就由你来决定如何布局。传统上你会超载operator>>
和operator<<
,但由于这看起来像家庭作业,这可能有点多。
你的代码还有其他几个问题…
您的case表达式不正确。您使用的值 1和2与1和2键的ASCII值不同。你应该使用'1'和'2',而不是简单的1和2。
您还应该开始检查您调用的函数(如
open
)返回的错误。检查
eof
在你的while循环是绝对不会工作的。参见Q&A @为什么循环条件中的iostream::eof被认为是错误的?
应该是:
switch(choice)
{
case '1':
EnterRecord();
break;
case '2':
ShowRecord();
break;
}
相关文章:
- 如何在ros2中从rosbag2读取数据
- OpenCV 和从 OutputArrays 或 (Mat) 读取数据
- 使用C++从磁卡读卡器MT188读取数据
- HDF5 简单读取数据集失败
- 嵌套结构,从由空行分隔的文件中读取数据
- 不要从输入队列套接字读取数据
- 从文件中读取数据,操作员>>
- 如何从excel文件中读取数据并存储到变量中?
- C++:从文件中读取x y数据会产生无限循环吗
- 无法通过FT232RL读取数据
- 如何从QNetworkReply读取数据?
- C++ 逐行从文件(包含空格)读取数据
- 通过显示一行星号来创建条形图,该条形图将读取数据的输入文件
- 我们可以从 TXT 文件中读取数据并使用 C 和 C++ 将其保存到 SQL 数据库吗?
- 从多个 tcp 连接读取数据
- 从文本文件中读取数据并删除所有换行符空格,并在 C++ 控制台中显示
- Qt TCP服务器不从客户端读取数据
- 累积从 C++11 中的文件中读取数据的整数
- 从 txt 文件中读取数据的最简单方法
- 从 txt 文件中读取数据的 Getline