Hi all,
Having some trouble with an assignment. My program should store lists of names and ages and sort the list by name (alphabetic).
Here's my current attempt
#include<stdio.h>
#include<string.h>
// struct to hold the data
typedef struct _data
{
char name[5][30];
int age[5];
} data;
int main()
{
data s;
int i, j;
char temps[30];
int tempa;
printf("Enter values, name then age>\n");
for(i=0;i<5;i++) // get user inputs
{
scanf("%s",s.name[i]);
scanf("%d",s.age);
printf("\n");
}
// bubble sort to get alphabetized list
for(j=0;j<5;j++)
{
for(i=0;i<5;i++)
{
if( strcmp(s.name[i],s.name[i+1]) >0) // if bigger
{
// swap names
strcpy(temps, s.name[i]);
strcpy(s.name, s.name[i+1]);
strcpy(s.name[i+1], temps);
// swap ages
tempa = s.age[i];
s.age[i] = s.age[i+1];
s.age[i+1] = tempa;
}
}
}
printf("\nAplhabetised List>\n");
for(i=0;i<5;i++)
{
printf("%s %d\n",s.name[i], s.age[i]);
}
} // end main
It's giving me really strange results, any idea what's up with it? It's my first time using a struct :$ so is the problem there?
Thanks in advance