Alex Razvan Alex Razvan - 9 days ago 4
C++ Question

Invalid conversion from 'char' to 'const char*' while using strcpy

Can't use strcpy, to properly swap char array. I used strncpy, memcpy everything and still didn't get the right result.

This is how my program looks.

class Carte
{
protected:
char Denumire[50];
char Autor[50];
char Editura[50];
int AnPublicare[50];
public:
void Citire(int n)
{
for(int i=0;i<n;i++)
{
cout<<"Denumire: "; cin>>Denumire[i]; cout<<endl;
cout<<"Autor: "; cin>>Autor[i]; cout<<endl;
cout<<"Editura: "; cin>>Editura[i]; cout<<endl;
cout<<"An Publicare: "; cin>>AnPublicare[i]; cout<<endl;
}
}

void Afisare(int n)
{
for(int i=0;i<n;i++)
{
cout<<"Denumire: "<<Denumire[i]<<endl;
cout<<"Autor: "<<Autor[i]<<endl;
cout<<"Editura: "<<Editura[i]<<endl;
cout<<"An Publicare: "<<AnPublicare[i]<<endl<<endl;
}
}


This where the problem is located.

void Sortare(int n)
{
int ok,aux;
char *auxDen , *auxAt, *auxEd;
do{
ok=1;
for(int i=0;i<n-1;i++)
if(AnPublicare[i]>AnPublicare[i+1])
{
ok=0;
aux=AnPublicare[i];
AnPublicare[i]=AnPublicare[i+1];
AnPublicare[i+1]=aux;

strcpy(auxDen,Denumire[i]);
strcpy(Denumire[i],Denumire[i+1]);
strcpy(Denumire[i+1],auxDen);

strcpy(auxAt,Autor[i]);
strcpy(Autor[i],Autor[i+1]);
strcpy(Autor[i+1],auxAt);

strcpy(auxEd,Editura[i]);
strcpy(Editura[i],Editura[i+1]);
strcpy(Editura[i+1],auxEd);
}
}while(ok!=1);
}
};


How can make it work?

Answer

In C array of char is a single string, so first of all your data types are wrong. You better use std::string which acts like a single string object:

class Carte
{
protected:
    std::string Denumire[50];
    std::string Autor[50];
    std::string Editura[50];
    int AnPublicare[50];

then moving them whould be the same as for int:

std::string tmp;
tmp = Denumire[i];
Denumire[i] = Denumire[i+1];
Denumire[i+1] = tmp;

or even better:

std::swap( Denumire[i], Denumire[i+1] );

if you are limited to C types you have to create array of arrays of char to keep 50 strings.