读书人

c++文件操作小问解决思路

发布时间: 2012-03-11 18:15:38 作者: rapoo

c++文件操作小问
用文件data.dat保存一个结构数组stu[3],
再读取文件内容,把文件内容到结构数组copy[3],
但是报错error C2106: '= ' : left operand must be l-value
请问如何修改,谢谢

具体程序如下

#include <iostream.h>
#include <fstream.h>
struct student
{
char name[20];
char num[10];
int score;
};
void main()
{
student stu[3]={{ "nihao ", "1541 ",90},{ "gsdhao ", "1542 ",93},{ "nfado ", "1543 ",95}};
student s;
student copy[3];
fstream f1;
f1.open( "data.dat ",ios::out|ios::in|ios::binary);

if(!f1)
{
cout < < "no open " < <endl;
return;
}

for(int i=0; i <3;i++)
{f1.write((char*)&stu[i],sizeof(student));}

f1.seekp(sizeof(student)*1);
f1.read((char*)&s,sizeof(student));
cout < <s.name < < "------------ " < <s.num < < "---------- " < <s.score < <endl;

for(int n=0; n <3;n++)
{
f1.seekp(sizeof(student)*n);
f1.read((char*)&s,sizeof(student));
copy[n].name=s.name;//有错误(error C2106: '= ' : left operand must be l-value)???
copy[n].num=s.num;//有错误(error C2106: '= ' : left operand must be l-value)???
copy[n].score=s.score;
cout < <copy[n].name < < "------------ " < <copy[n].num < < "---------- " < <copy[n].score < <endl;

}

}

[解决办法]
C字符串的值不能用=
你用memmove或strcpy(注意源、目字符串末尾的NULL)
[解决办法]
字符串赋制值错,不能用=
用strcpy(copy[n].name,s.name);

读书人网 >VC/MFC

热点推荐