鱼C论坛

 找回密码
 立即注册
查看: 3991|回复: 2

c++二进制文件怎么读取对应的字符

[复制链接]
发表于 2013-8-3 20:30:42 | 显示全部楼层 |阅读模式
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]数组
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2013-8-3 20:30:43 | 显示全部楼层
因为string内部没有保存整个字符数组,仅仅保存了一个char*指针,指向某个字符数组。当你read的时候,仅仅恢复了该指针的值,但此时,指针锁指向的内容已经被删除了。你可以不使用string,改用char[100]数组
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2013-8-3 21:27:11 | 显示全部楼层
sizeof(std)是返回std对象的大小,而不是字符串的长度
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-16 06:30

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表