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

line 6 is wrong scanf("%d", &s.age[i]); And the sort algorithm needs some twinking. line 34: Its not necessary to check from 0 to current value of j because they are already in order. for(i=i+1;i<5;i++) And the swaps should use j and i, not i and i+1.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.