gpt4 book ai didi

c++ - 如何将对象数组中的内容复制到 C++ 中的另一个数组中?

转载 作者:行者123 更新时间:2023-11-28 06:42:04 25 4
gpt4 key购买 nike

#include "stdafx.h"
#include<iostream>
using namespace std;
class bank
{
public: char name[20];
public: float balance;
public: void get()
{
cout << "\nEnter name and balance in Account respectively\n";
cin >> name >> balance;
}
public: void display()
{
cout << "Name: " << name << " Balance: " << balance;
}
};
void main()
{
int i = 0;
bank b[10];
bank max;
bank temp;
for (i = 0; i < 10; i++)
{
b[i].get();
}
for (i = 0; i < 10; i++)
{
if (b[i + 1].balance > b[i].balance)
{
max.balance = b[i + 1].balance;
max.name = b[i + 1].name;//Error 1 error C2106: '=' : left operand must be l-value
}
else
{
temp.balance = b[i + 1].balance;
temp.name = b[i + 1].name;//Error 2 error C2106: '=' : left operand must be l-value
b[i + 1].balance = b[i].balance;
b[i + 1].name = b[i].name;//Error 3 error C2106: '=' : left operand must be l-value
b[i].balance = temp.balance;
b[i].name = temp.name;//Error 4 error C2106: '=' : left operand must be l-value
max.balance = b[i + 1].balance;
max.name = b[i + 1].name;//Error 5 error C2106: '=' : left operand must be l-value
}

}
max.display();
}

在这个程序中,我必须将输入作为 10 个人的姓名和余额,并将输出显示为对应于最高余额的姓名和余额。除了代码本身作为注释显示的错误之外,我还在相同的那些行中获得了另一个代码,仅在我对错误进行注释的地方。另一个错误是:

IntelliSense: expression must be a modifiable lvalue

我使用的是 Visual Studio Professional 2013,代码是 Visual C++

最佳答案

您不能分配 char[]变量到另一个char[]多变的。你应该使用 strcpy功能来做到这一点(并且不要忘记先include<cstring>)。看到这个 how to copy char array to another char array in C?进一步解释。

如果这样改,应该没问题:

#include<iostream>
#include<cstring>
using namespace std;
class bank
{
public: char name[20];
public: float balance;
public: void get()
{
cout << "\nEnter name and balance in Account respectively\n";
cin >> name >> balance;
}
public: void display()
{
cout << "Name: " << name << " Balance: " << balance;
}
};
void main()
{
int i = 0;
bank b[10];
bank max;
bank temp;
char tempstr[20]; // use this for temporary string
for (i = 0; i < 3; i++)
{
b[i].get();
}
for (i = 0; i < 2; i++) // you should change the upper bound to 9
// so it not crash when i = 9
{
if (b[i + 1].balance > b[i].balance)
{
max.balance = b[i + 1].balance;
strcpy(max.name, b[i+1].name); // use strcpy
}
else
{
temp.balance = b[i + 1].balance;
strcpy(temp.name, b[i+1].name); // use strcpy
b[i + 1].balance = b[i].balance;
strcpy(b[i+1].name, b[i].name); // use strcpy
b[i].balance = temp.balance;
strcpy(b[i].name, temp.name); // use strcpy
max.balance = b[i + 1].balance;
strcpy(max.name, b[i+1].name); // use strcpy
}

}
max.display();
}

关于c++ - 如何将对象数组中的内容复制到 C++ 中的另一个数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25810338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com