Qsort issue (Also how to sort alphabetically.)

hi everyone. i have an issue on my hands. basically i have entered a program where i enter the names of students, with data binded to them, i then have to print them out in alphabetical order. thats it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
 #include "stdafx.h" 
#include <stdio.h>
#include <string.h>
 #include <conio.h> 
#include <stdlib.h>
 
 
#define NO_OF_STUDENTS 4       

struct data {
  char name[20];
  int age;
  int weight;
};
 
int main()
{
  struct data Students[NO_OF_STUDENTS]; // 20 students.
  int Counter = 0;
 
  for (Counter = 0; Counter < NO_OF_STUDENTS; ++Counter) {
    scanf("%s", Students[Counter].name);
    scanf("%d", &Students[Counter].age);
    scanf("%d", &Students[Counter].weight);
  }
 
  


  
  qsort(Students[NO_OF_STUDENTS],4,sizeof(int),compare);

  for (Counter = 0; Counter < NO_OF_STUDENTS; ++Counter) {
    printf("Name=%s, ", Students[Counter].name);
    printf("Age=%d, ", Students[Counter].age);
    printf("Weight=%d\n", Students[Counter].weight);
  }
  

//////////////////////////////Need some sort of alphabetically sorting method here, dont know if there is on in c++...


  getch();
 
  return 0;
}





int compare (const void * a, const void * b)
{
  return ( *(int*)a - *(int*)b );
}


Last edited on
For qsort() you need to provide:

1. The start of the array
2. The number of elements of that said array
3. The size of one element of that said array
4. The compare function

qsort(Students, sizeof(Students) / sizeof(*Students),sizeof(*Students),compare);

In the compare function you have to deal with the provided data:

1
2
3
4
5
6
7
int compare (const void * a, const void * b) // Example: sorted by name
{
  const data *da = (const data *) a;
  const data *db = (const data *) b;
  return strcmp(da->name, db->name); // Note: negative value -> less than, 0 -> equal to, positive value -> greater than. strcmp() does return that

}


Need some sort of alphabetically sorting method here, dont know if there is on in c++...
C++ provides std::sort(): http://www.cplusplus.com/reference/algorithm/sort/
Last edited on
Topic archived. No new replies allowed.