Ireland1978
Programmer
I've only been doing C for a few weeks, and could really do with some help with this please.
I'm attempting to write code that will take in first names, last names and ages, then prints them alphabetically to the screen, with the correct first names, last names and ages.
I'm just trying to sort the last name array first, but I can't see where I'm going wrong in this, when I run it I just get rubbishy output. When I debug it and step through it, it seems to be comparing the letters in the fname array.
I haven't even STARTED trying to work out how to get the other two arrays to match the lname one once they're sorted!
Any help greatly appreciated! Thanks
I'm attempting to write code that will take in first names, last names and ages, then prints them alphabetically to the screen, with the correct first names, last names and ages.
I'm just trying to sort the last name array first, but I can't see where I'm going wrong in this, when I run it I just get rubbishy output. When I debug it and step through it, it seems to be comparing the letters in the fname array.
Code:
/* Store lists of names (surname first) and ages in parallel arrays
Sort the names into alphabetical order
keeping the ages with the correct names. */
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define CLASS_SIZE 3
#define NAME_LEN 15
int strncmp(const char *s1, const char *s2, size_t n);
int main (void) {
char lname[CLASS_SIZE][NAME_LEN]; /*Declare array of char*/
char fname[CLASS_SIZE][NAME_LEN], temp;
int age[CLASS_SIZE];
for(int i=1; i<=CLASS_SIZE; i++){
printf("Enter first name, last name and age please:\n");
scanf("%s %s %d", fname, lname, &age);
}
for (int x=0; x<CLASS_SIZE; x++) { /*Outer loop to go through each element of array*/
for (int y=1; y<NAME_LEN; y++){ /* Loop through the elements of each name */
if ((strncmp(lname[y-1], lname[y],NAME_LEN )>0)){
temp = *lname[y]; /* Compare strings, swap if necessary */
*lname[y] = *lname[y-1];
*lname[y-1] = temp;
}
}
}
for(int a=1; a<=CLASS_SIZE; a++)
printf("%s\n", lname[a] ); /* Print ordered names to screen */
return 0;
}
I haven't even STARTED trying to work out how to get the other two arrays to match the lname one once they're sorted!
Any help greatly appreciated! Thanks