注册 登录
编程论坛 C++教室

对象数组与文件问题

机器王者 发布于 2013-07-04 16:36, 539 次点击
请教大神,如何将动态的对象数组写入文件,并可读出显示到屏幕,其间还可以增添对象,能否给个例子,3Q
3 回复
#2
yuccn2013-07-04 20:39
不知道你具体想干什么,
#3
机器王者2013-07-04 21:06
回复 2楼 yuccn
就比如,把数组a[3]={1,2,3}储存在一个文件里,想要的时候读出来就行了
#4
Pirelo2013-07-05 09:33
要写入文件,建议你研究一下文件流fstream:
char *file;
ofstream out(file,ios::out);
然后像使用输入输出流cout一样,使用文件流out;
区别是cout输出到计算机显示设备,文件流定义的out输出到绑定的文件file;

例如对于类A;
#include<fstream>
#include<iostream>
#include<string>
using namespace std;
class A{
public:
A(int a, int b, int c):x(a),y(b),z(c){}
int x;
int y;
int z;
};

void main()
{
  A a(1,2,3);
  string file;
  cout<<"please input the file to be wrote:\n";
  getline(cin,file);
  ofstream out(file.c_str(),ios::out);
  //output to screen:
  cout<<a.x<<a.y<<a.z<<endl;
  //output to file:
  out<<a.x<<a.y<<a.z;
  out.close();
  return;
}

[ 本帖最后由 Pirelo 于 2013-7-5 09:42 编辑 ]
1