我收到一个错误:
expression must be a modifiable lvalue at line,
obj.name = ptr->name
我试过像这样使obj成为数组类型的对象
for(int j=0 ;j<1;j++)
{
obj[j].id = ptr->id;
obj[j].balance= ptr->balance;
obj[j].name = ptr->name; //still getting error here.
obj[j].nic = ptr->nic;
}
return(obj);
}
但这也没有用。
如果我注释掉错误并只传递三个剩余值,它应该可以工作,但我在第一个输出后收到垃圾值。
原代码如下:
#include<iostream>
using namespace std;
struct bank
{
int id, nic;
float balance;
char name[20];
};
bank search(bank* );
void main()
{
bank data[2],mobj;
for(int i=0;i<2;i++)
{
cout<<"enter name: ";
cin>>data[i].name;
cout<<"enter id: ";
cin>>data[i].id;
cout<<"enter balance : ";
cin>>data[i].balance;
cout<<"enter nic : ";
cin>>data[i].nic;
}
mobj=search(data);
cout <<"balance of customer no. "<<mobj.balance<<endl;
cout<<"id is" <<mobj.id<<endl;
cout<< "nic is"<<mobj.nic<<endl;
system("pause");
}
bank search(bank *ptr)
{
int id;
cout<<"enter value you want to serch"<<endl;
cin>>id;
bank obj;
for(int i=0 ; i<2 ;i++)
{
if(ptr->id == id)
{
break;
}
ptr++;
}
obj.id = ptr->id;
obj.balance= ptr->balance;
obj.name = ptr->name; //error in this line(obj must be modifiable value)
obj.nic = ptr->nic;
return(obj);
}
请在您认为合适的时候提供帮助!
最佳答案
obj.name
是一个char
数组。您不能对数组进行赋值。所以如果你想坚持使用数组:
- 参见 c++ array assignment of multiple values
- 使用
strcpy(obj.name, ptr->name);
但我建议转换为 std::string
...它比数组更容易使用,在我看来你打算使用 obj.name
作为字符串。所以得到了正确的字符串。
关于c++ - 错误 : expression must be a modifiable lvalue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25381071/