C++ 更新结构
C++ Update Struct
我有这个:
typedef struct {
char nome[50];
char morada[100];
char codpostal[8];
char localidade[30];
int telefone;
int nContribuinte;
} CLIENTE;
CLIENTE c;
如何像 c.nome = "something";
一样更新 c.nome
?无法弄清楚为什么这行不通...c
已经填充了保存在二进制文件中的已知信息
我应该这样做:if (Conf == 1) { scanf("%s", c.nome); } else { c = Clt.nome; }
对于类 C 的字符串,使用 strcpy(),像这样:
strcpy(c.nome, "something");
您尝试的方法不起作用的原因是您使用了类似 C 的字符串,而不是 std::string,这是 C++ 方法,并且重载了赋值运算符。在那种情况下,您的结构将如下所示:
#include <string>
struct CLIENTE {
std::string nome;
...
};
CLIENTE c;
c.nome = "something";
您可以避免 typedef,如 Difference between 'struct' and 'typedef struct' in C++?:
中所述
In C++, all struct declarations act like they are implicitly
typedef'ed, as long as the name is not hidden by another declaration
with the same name.
我有这个:
typedef struct {
char nome[50];
char morada[100];
char codpostal[8];
char localidade[30];
int telefone;
int nContribuinte;
} CLIENTE;
CLIENTE c;
如何像 c.nome = "something";
一样更新 c.nome
?无法弄清楚为什么这行不通...c
已经填充了保存在二进制文件中的已知信息
我应该这样做:if (Conf == 1) { scanf("%s", c.nome); } else { c = Clt.nome; }
对于类 C 的字符串,使用 strcpy(),像这样:
strcpy(c.nome, "something");
您尝试的方法不起作用的原因是您使用了类似 C 的字符串,而不是 std::string,这是 C++ 方法,并且重载了赋值运算符。在那种情况下,您的结构将如下所示:
#include <string>
struct CLIENTE {
std::string nome;
...
};
CLIENTE c;
c.nome = "something";
您可以避免 typedef,如 Difference between 'struct' and 'typedef struct' in C++?:
中所述In C++, all struct declarations act like they are implicitly typedef'ed, as long as the name is not hidden by another declaration with the same name.