|
1鱼币
我想输入学号能读出学号对应的姓名,
输入某个数字,就能打印出这个数字和对应的姓名
--------------------------------------------------------------代码-----------------------------------------------------------------------
#include<iostream>
#include <string.h>
#include <fstream>
#include <string>
using namespace std;
struct student
{
string number;
string subject;
};
//二进制文件写入学号
void addstudent()
{
student std;
cout<<"输入学号:"<<endl;
cin>>std.number;
fstream f;
f.open("text.txt",ios::out|ios::app|ios::binary);
f.write((char *)&std,sizeof(std));
f.close();
}
//先判断学号是否存在,如果存在就写入科目
void setsubject()
{
student std;
string inputnum;
cout<<"输入学号"<<endl;
cin>>inputnum;
string inputsub;
cout<<"输入学科"<<endl;cin>>inputsub;
fstream f2;
f2.open("text.txt",ios::out|ios::app|ios::binary);
for(int i=0;i<10;i++)
{
f2.read((char *)&std,sizeof(std));//读出文件中的所有数据
if(inputnum==std.number) //先判断学号是否存在
{
std.subject=inputsub; //将cin的输入的科目付给std.subject
//strcpy(std.subject,inputsub);
f2.seekp(-sizeof(std),ios::cur);//这句我不知道什么意思 谁能解释下- -
f2.write((char *)&std,sizeof(std));//写到对应学号的科目
}
}
f2.close();
}
void main()
{addstudent();
setsubject();
student std1;
//-------------这里是输入学号能读出学号对应的科目------但是显示不出来--------哪里错了?
fstream f3;
f3.open("text.txt",ios::out|ios::app|ios::binary);
cout<<"输入学号验证"<<endl;
string num;
cin>>num;
for(int i=0;i<10;i++)
{
f3.read((char *)&std1,sizeof(std1));
if(num==std1.number)
{
f3.seekp(-sizeof(std1),ios::cur);
cout<<std1.number;
}
}
f3.close();
}
|
最佳答案
查看完整内容
因为string内部没有保存整个字符数组,仅仅保存了一个char*指针,指向某个字符数组。当你read的时候,仅仅恢复了该指针的值,但此时,指针锁指向的内容已经被删除了。你可以不使用string,改用char[100]数组
|