Hello cplusplus community. I was trying to solve a little problem from a tutorial to learn c++ and i've come to an impassable wall (for me of course :D).
In the assignment we had to create a small database using structures and arrays and then search through it.
My problem comes when i try to assign names to the arrays. I get this error line: incompatible types in assignment of 'const char [5]' to 'char [20]'
And it variates depending on the length of the name.
That is not the assignment that you are looking for.
What you try to do now is essentially:
1 2 3
constchar * a;
char * b;
b = a;
What you should do is to copy elements from one array into an another. Check <cstring> for C-string copying functions. Better yet, replace char arrays with std::string. It has a copy assignment operator.
The differences between the data type "const char[5]" and the data type "char[20]" seem negligible to humans, but to the compiler, trying to set a variable of date type "const char[5]" to a variable of data type "char[20]" makes about as much sense as int x='a';
"jose" is const char[5] because the string literal "jose" will always be "jose".
I ran into the same problem when I started programming and the explanation didn't make sense to me until much later, but fortunately the fix is simple.
I have one question. Keskiverto said that i should replace char arrays with std::string. is that using the function strcpy?
I also have another problem with this little program and i can't find where it is.
After fixing the const char issue i ran the program but i failed to do so. When i search for any name or telephone number [except for the first one in the list(jose - 12345678)] i get an infinite amount of prints with the results.
#include <string>
struct persona
{
std::string nombre; // Change this to std::string
int telefono;
} lista[10];
int main()
{
// asignacion de valores a la estructura
lista[1].nombre = "jose"; // This works like you would expect -- no strcpy needed
lista[1].telefono = 12345678;
lista[2].nombre = "juan";
lista[2].telefono = 34265891;
// etc.