C++文件读写

demystify 2014-09-14 11:25:51
网上找的一段文件读写的代码,自己测试发现了一些问题,希望大家帮助
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

class Sprite
{
private:
std::string profession;//职业
std::string weapon;//武器
static int count;//个数
public:
Sprite(){}
Sprite(std::string profession,std::string weapon):profession(profession),weapon(weapon)
{
}
void showSprite();//显示精灵信息
};

int Sprite::count=0;

void Sprite::showSprite()
{
++count;
std::cout<<"精灵"<<count<<" 职业:"<<profession<<" 武器:"<<weapon<<std::endl;
}
void write_bin()
{
Sprite sprite[3] =
{
Sprite("法师", "魔杖"),
Sprite("战士", "屠龙宝刀"),
Sprite("道士","倚天剑")
};

//打开文件
ofstream ofile("file.dat", ios::binary | ios::ate);
if(!ofile)
{
cout<<"打开文件失败!"<<endl;
exit(1);
}

for(int i=0; i</*sizeof(sprite)/sizeof(sprite[0])*/3; i++)
{
ofile.write( (char*)&sprite[i], sizeof(sprite[i]));
ofile.flush();
}

//关闭文件
ofile.close();
}

void read_bin()
{
Sprite sprite[3];

ifstream ifile("file.dat", ios::binary);
if(!ifile)
{
cout<<"打开文件失败!"<<endl;
exit(1);
}

ifile.seekg(/*i*sizeof(Sprite)*/0, ios_base::beg);
for(int i=0; i<3; i++)
{

ifile.read((char*)&sprite[i], sizeof(sprite[i]));
sprite[i].showSprite();
}

ifile.close();
}

int _tmain(int argc, _TCHAR* argv[])
{
write_bin();
read_bin();
while(1);
return 1;
}

该段代码在VC6.0下运行:显示到屏幕的是乱码,VS2010下执行:运行时报错。
将Sprite类的string类型成员改为char型数组就运行正常。
这是什么原因造成的?
...全文
117 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
赵4老师 2014-09-15
  • 打赏
  • 举报
回复
崩溃的时候在弹出的对话框按相应按钮进入调试,按Alt+7键查看Call Stack里面从上到下列出的对应从里层到外层的函数调用历史。双击某一行可将光标定位到此次调用的源代码或汇编指令处。
Arnis1973 2014-09-14
  • 打赏
  • 举报
回复
用错函数类型
derekrose 2014-09-14
  • 打赏
  • 举报
回复
看stack信息
demystify 2014-09-14
  • 打赏
  • 举报
回复
报错信息如图所示:

64,637

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧