2

I have this:

typedef struct {
    char nome[50];
    char morada[100];
    char codpostal[8];
    char localidade[30];
    int telefone;
    int nContribuinte;
} CLIENTE;
CLIENTE c;

How do I update c.nome like c.nome = "something";? Can't figure out why wouldn't this work... c has already been filled with known info saved on a binary file

I'm supposed to do this: if (Conf == 1) { scanf("%s", c.nome); } else { c = Clt.nome; }

gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • 4
    You don't need a `typedef` for `struct`s in c++, you could just name it. –  May 09 '17 at 16:16
  • 2
    Advice --- Stop writing `C` code. – PaulMcKenzie May 09 '17 at 16:17
  • 1
    In C++ arrays are non assignable, you can use a function to fill it out with your string literal, `strcpy` would work. Just make sure you've enough space for a nul terminator or some serious sadness will occur :-) – George May 09 '17 at 16:18

1 Answers1

3

For C-like strings, use strcpy(), like this:

strcpy(c.nome, "something");

The reason what you tried didn't work is that you used C-like strings, and not std::string, which is the C++ approach, and has overloaded the assignment operator. In that case your struct would look like this:

#include <string>

struct CLIENTE {
    std::string nome;
    ...
};
CLIENTE c;
c.nome = "something";

You can avoid the typedef, as described in 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.

Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305