关于#c++#的问题:结构体CandyBar,往第一个成员里赋值程序报错,显示表达式必须是可更改的左值

结构体CandyBar,往第一个成员里赋值程序报错,显示表达式必须是可更改的左值,求指教。


#include 
#include 
using namespace std;

const int SLEN=30;
struct CandyBar{
    char Name[SLEN];
    double weight;
    int heat;
};
void setinfo(CandyBar c, string nam, double w)
{
    c.Name= nam;//报错
    c.weight = w;
    c.heat = 350;
}
void display(CandyBar cc)
{
    cout << "The name is" << cc.Name << endl;
    cout << "The weight is" << cc.weight << endl;
    cout << "The heat is" << cc.heat << endl;
}
int main()
{
    CandyBar cc;  
    //用后面的三个参数值,完成对第一个参数变量cc 的初始化)
    setinfo(cc,"WW",3.35);
    //显示参数cc的具体信息,显示格式如下:
    //The name is WW
    //The weight 3.35 
    //The heat is 350 
    display(cc);
}
  • 字符数组 赋值,用strcpy;
  • string 赋值给 char数组,参考如下:
strcpy(c.Name,nam.c_str());

该回答引用ChatGPT

在函数setinfo中,参数c是一个结构体变量,但是它传递的是值参数,这意味着函数将会复制一份结构体变量,而不是直接修改原始的结构体变量。所以在给c.Name赋值时,会报错提示表达式必须是可更改的左值。

要解决这个问题,可以将参数c改为引用传递,这样函数就可以直接修改原始的结构体变量。修改代码如下:

void setinfo(CandyBar& c, string nam, double w)
{
    strcpy(c.Name, nam.c_str());
    c.weight = w;
    c.heat = 350;
}

这里使用strcpy函数将nam的内容复制到c.Name中,注意需要使用c_str()函数将string类型的参数转换为C风格的字符串。