Sorting arrays help.

Hey guys, i missed class this week and i had a assignment due and i am just completely lost can someone help me with my program. I need to get the user to input there student id and GPA and arrange them in descending order.

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
  // Example program
#include <iostream>
#include <string>

struct student {
 int id;
 double gpa;
};


int main() {
    struct student s[10];
    int i,j;
    int temp;
    int temp1;
  
    for (i = 1; i<10; i++) { std::string input;
        std::cout << "What is your ID (5 digits) (-1 to Exit)? ";
        getline (std::cin, input);
        int id = atoi(input.c_str());
        printf("Received %d", id);
      
        if (id == -1) {
            break;
        }   
        std::cout << "What is your GPA? ";
        getline (std::cin, input);
        double gpa = atof(input.c_str());
        printf("Received %1.1f", gpa);
    }
    for (i = 1; i<10; i++) {
        if (s[i].gpa < s[j].gpa) {
            temp = s[i].gpa;
            s[i].gpa = s[j].gpa;
            s[j].gpa = temp;
        
            temp1 = s[i].id;
            s[i].id = s[j].id;
            s[j].id = temp1;
        }
        printf("\nSorted array:");
        for (i = 1; i<10; i++) {
            printf("%d   ", s[i].id);
            printf("%lf \n ", s[i].gpa);
        }
   }
   
   return 0;
}
Your data-entry section (lines 18-29) is unnecessarily complicated, as it's a struct (public access) you can std::cin directly into the data-members of the student objects:
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
#include <iostream>
#include <utility>

constexpr auto SIZE = 10;

struct student {
 int id;
 double gpa;
};

int main()
{
    student s[SIZE];
    for (auto i = 0; i < SIZE; ++i)
    {
        std::cout << "enter id of student# " << i + 1 << "\n";
        std::cin >> s[i].id;
        std::cout << "enter gpa of student# " << i + 1 << "\n";
        std::cin >> s[i].gpa;
    }
    for (auto i = 0; i < SIZE; ++i)
    {
        for (auto j = i + 1; j < SIZE; ++j)
        {
            if(s[i].gpa < s[j].gpa)
            {
                std::swap(s[i], s[j]);
            }
        }
    }
    for (auto i = 0; i < SIZE; ++i)
    {
        std::cout << s[i].id << " " << s[i].gpa << "\n";
    }
}
Topic archived. No new replies allowed.