不能使用strcpy来正确交换char数组。我使用strncpy,memcpy所有东西,但仍然没有得到正确的结果。
这就是我的程序的样子。
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;
}
}
问题出在哪里。
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);
}
};
如何使其有效?
答案 0 :(得分:1)
在C数组中,char是一个单独的字符串,所以首先你的数据类型是错误的。最好使用std::string
,它就像一个字符串对象:
class Carte
{
protected:
std::string Denumire[50];
std::string Autor[50];
std::string Editura[50];
int AnPublicare[50];
然后移动它们与int
:
std::string tmp;
tmp = Denumire[i];
Denumire[i] = Denumire[i+1];
Denumire[i+1] = tmp;
甚至更好:
std::swap( Denumire[i], Denumire[i+1] );
如果您只限于C类型,则必须创建char数组数组以保留50个字符串。
答案 1 :(得分:1)
char
只是一个字符;你似乎把它当成一个完整的字符串。如果可以,最好使用std::string
代替char*
,因为它们更容易正确使用。
另外,我建议您将所有元素分组到一个struct Book
。这样一切都在一起,你可以使用现有的STL排序算法,这将更快。
#include <string>
#include <vector>
#include <algorithm>
struct Book{
std::string Denumire;
std::string Autor;
std::string Editura;
int AnPublicare;
};
bool publisherLessThan(const Book& a, const Book& b) {
return a.AnPublicare < b.AnPublicare;
}
class Carte
{
protected:
std::vector<Book> books;
public:
void Citire(int n)
{
books.clear();
for(int i=0;i<n;i++)
{
Book book
cout<<"Denumire: "; cin>>book.Denumire; cout<<endl;
cout<<"Autor: "; cin>>book.Autor; cout<<endl;
cout<<"Editura: "; cin>>book.Editura; cout<<endl;
cout<<"An Publicare: "; cin>>book.AnPublicare; cout<<endl;
books.push_back(book);
}
}
void Afisare()
{
for(const Book& book : books)
{
cout<<"Denumire: "<<book.Denumire<<endl;
cout<<"Autor: "<<book.Autor<<endl;
cout<<"Editura: "<<book.Editura<<endl;
cout<<"An Publicare: "<<book.AnPublicare<<endl<<endl;
}
}
void Sortare() {
std::sort(books.begin(), books.end(), publisherLessThan);
}
};