void func1()
{
ofstream output("book.in");
Book book1;
int n;
cout<<"input data"<<endl;
cout<<"how many books?";
cin>>n;
for(int i=0;i<n;i++)
{
cout<<"the "<<(i+1)<<"st book"<<endl;
book1.getdata();//getdata是给对象每个成员的赋值函数
output.write((char *)&book1,sizeof(book1));//写入到文件
};
output.close();
}
void func2()
{
fstream file("book.in",ios::in);
Book book1;
Book book[100];
int i=0;
cout<<"output data"<<endl;
cout<<"bookname number"<<endl;
while(1)//想用从文件中读取的数据给对象数组赋值
{
file.read((char *)&book1,sizeof(book1));
if(!file) break;
book[i]=book1;
i++;
}
file.close();
}
int main()
{
func1();
func2();
system("pause");
return 0;
}
程序运行时存在问题,可以写入,但无法给数组赋值,恳请高手赐教...
5 个解决方案
#1
book[i]=book1;
你最好自己重载一个运算符号,自定义赋值方式,这样默认就是浅拷贝
你最好自己重载一个运算符号,自定义赋值方式,这样默认就是浅拷贝
#2
把全部的代码都贴出来吧
#3
帮顶~
#4
考虑对Book类重载输入输出运算符,>>和<< ~
使用read/write,一般针对二进制文件,文件打开时需增加属性ios::binary
使用read/write,一般针对二进制文件,文件打开时需增加属性ios::binary
#5
#include "iostream"
#include "string"
#include "fstream"
using namespace std;
struct book
{
int id;
int page;
string name;
};
istream& operator>> (istream& i, book& bk)
{
i>>bk.id>>bk.page>>bk.name;
return i;
}
ostream& operator<< (ostream& o, const book& bk)
{
o<<bk.id<<" "<<bk.page<<" "<<bk.name<<endl;
return o;
}
int main()
{
const int test_num = 5;
book books1[test_num];
book books2[test_num];
ofstream ofile("file.in");
for (int i = 0; i < test_num; ++i)
{
cin>>books1[i];
ofile<<books1[i];
}
ofile.close();
cout<<endl;
ifstream ifile("file.in");
if (ifile.fail())
return 1;
for (int i = 0; i < test_num; ++i)
{
ifile>>books2[i];
cout<<books2[i];
}
ifile.close();
return 0;
}
--------
1 100 aaa
2 100 bbb
3 100 ccc
4 100 ddd
5 100 eee
1 100 aaa
2 100 bbb
3 100 ccc
4 100 ddd
5 100 eee
#1
book[i]=book1;
你最好自己重载一个运算符号,自定义赋值方式,这样默认就是浅拷贝
你最好自己重载一个运算符号,自定义赋值方式,这样默认就是浅拷贝
#2
把全部的代码都贴出来吧
#3
帮顶~
#4
考虑对Book类重载输入输出运算符,>>和<< ~
使用read/write,一般针对二进制文件,文件打开时需增加属性ios::binary
使用read/write,一般针对二进制文件,文件打开时需增加属性ios::binary
#5
#include "iostream"
#include "string"
#include "fstream"
using namespace std;
struct book
{
int id;
int page;
string name;
};
istream& operator>> (istream& i, book& bk)
{
i>>bk.id>>bk.page>>bk.name;
return i;
}
ostream& operator<< (ostream& o, const book& bk)
{
o<<bk.id<<" "<<bk.page<<" "<<bk.name<<endl;
return o;
}
int main()
{
const int test_num = 5;
book books1[test_num];
book books2[test_num];
ofstream ofile("file.in");
for (int i = 0; i < test_num; ++i)
{
cin>>books1[i];
ofile<<books1[i];
}
ofile.close();
cout<<endl;
ifstream ifile("file.in");
if (ifile.fail())
return 1;
for (int i = 0; i < test_num; ++i)
{
ifile>>books2[i];
cout<<books2[i];
}
ifile.close();
return 0;
}
--------
1 100 aaa
2 100 bbb
3 100 ccc
4 100 ddd
5 100 eee
1 100 aaa
2 100 bbb
3 100 ccc
4 100 ddd
5 100 eee