[英]Assigning a string to a char array in a structure in Turbo C++
I should mention that I am on Turbo C++ (yes the old one) because it is required by my school. 我应该提到我正在使用Turbo C ++(是旧版本),因为我的学校要求这样做。
I have a structure like this: 我有这样的结构:
struct move{
int power;
int pp;
char name[10];
};
When I try to make a new variable if I do this: 当我尝试执行以下操作创建新变量时:
move tackle;
tackle.pp = 10;
tackle.power = 20;
tackle.name = "tackle";
I get an error as: 我收到如下错误:
Error NONAME00.CPP 11: Lvalue required
But this works: 但这有效:
move tackle = {20, 10, "tackle"}
it works. 有用。
What am I doing wrong? 我究竟做错了什么?
PS line 11 is the tackle.name = "tackle"
, sorry if I was unclear earlier. PS第11行是
tackle.name = "tackle"
,如果我之前不清楚,抱歉。
You can't assign to an array, but you can initialise it. 您不能分配给数组,但可以对其进行初始化。
tackle.name = "tackle";
is an assignment, while 是一项任务,而
move tackle = {20, 10, "tackle"};
is an initialisation. 是一个初始化。
To replace the contents of the array, use strcpy
: 要替换数组的内容,请使用
strcpy
:
strcpy(tackle.name, "tackle");
or, better, use string
if you're allowed to: 或者,如果允许,请使用
string
:
#include <string>
struct move{
int power;
int pp;
string name;
};
您正在使用c风格的字符串,应通过以下方式对其进行初始化
strcpy(tackle.name, "tackle");
This line 这条线
tackle.name = "tackle";
tries to assign one array to another which not a supported operation in C or C++. 尝试将一个数组分配给C或C ++中不支持的操作的另一个数组。
However initialization like char name[10] = "tackle"
is fine by the standard and is supported. 但是,标准支持并支持像
char name[10] = "tackle"
这样的初始化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.