When I call the function and then display it, the output is same as the input. There is no other error in the program, which should mean taht there is some problem in the function. I'm just a beginner so any help is appreciated.
#include <iostream>
using namespace std;
struct student
{
char name[30];
int marks;
void getinfo()
{
cout<< "Enter your name:\n"; cin>>name;
cout<<"Enter marks:\n"; cin>>marks;
}
void showinfo()
{
cout<<"\nName: "<<name<<endl;
cout<<"Marks: "<<marks<<endl<<endl;
}
};
void bubsort( student S[] , int N)
{
student Temp;
for(int i=0;i<N-1;i++)
for(int j=0;j<N-1-i;j++)
{
if(S[j].name>S[j+1].name)
{
Temp=S[j];
S[j]=S[j+1];
S[j+1]=Temp;
}
}
}
int main()
{
student A[5];
cout<<" Enter details for 5 students:\n";
for( int i=0;i<5;i++)
A[i].getinfo();
bubsort(A,5); //I used the function
cout<<" Sorted information:\n";
for( int j=0;j<5;j++)
A[j].showinfo(); //result is in the same order as input
}
Arrays decays to pointers, so your comparison S[j].name>S[j+1].name
is comparing pointers and not the strings.
If you want to compare string you need to use either std::string
instead of character arrays, or use strcmp
.