我正在尝试为某些目的创建多个文件,并将不同的数据集存储到它们中。但这段代码似乎没有用。还有另一个麻烦。我无法在输出窗口中输入教师姓名。请帮助我纠正此代码。 这是我用来做这一切的功能。
#include<iostream>
#include<fstream>
using namespace std;
struct teacher{
int id;
char name[50];
char subject[50];
char qualification[50];
char experience[50];
};
teacher teacher;
void addition(int a)
{
char ans='y';
do
{
teacher.id=a;
fstream sfile;
sfile.open("id.dat",ios::app|ios::out|ios::binary);
cout<<"\n enter the teacher name"<<endl;
gets(teacher.name);
cout<<"enter subject taught by teacher"<<endl;
gets(teacher.subject);
cout<<"enter qualification "<<endl;
gets(teacher.qualification);
cout<<"enter experience"<<endl;
gets(teacher.experience);
sfile.write((char*)&teacher,sizeof(teacher));
cout<<"continue... (y/n)";
cin>>ans;
sfile.close();
}
while(ans=='y');
}
int main(void)
{
int a,t_id;
cout<<"1:NEW TEACHER REGISTRATION AND TIME TABLE CREATION"<<endl;
cout<<"2:MODIFY EARLIER DATA"<<endl;
cin>>a;
char ans='y';
if (a==1)
{
cout<<"enter the teacher id";
cin>>t_id;
addition(t_id);
}
//please neglect case 2.
}
帮我编写代码,或者请建议任何其他更好的方法来执行此操作。 我想在每次调用此函数时生成多个文件。
答案 0 :(得分:0)
ios :: ate是一种用于读取文件的模式。
更改下面的代码:
sfile.open("t_id.dat",ios::ate); // should change the open mode, then. as follows
sfile.open("t_id.dat",ios::app|ios::out|ios::binary)
它会起作用。
答案 1 :(得分:0)
便宜的方法是将整数转换为字符串并将其附加到文件名,例如:
...
string filename("foo");
filename += std::to_string(a);
filename += ".dat";
...
没有这样的魔法可以通过查看你编写的代码来猜测你想要的东西。