Question

Write your question here.
Hello everyone. Question: Print the names of students who scored second lowest marks in a test. Encountering multiple problems(errors). Please help.
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
#include <bits/stdc++.h>
using namespace std;

class students
{
    string name;
    int marks;
  public:
        void students :: size();
         void getdata()
         {
             for(int i=0;i<3;i++)
             {
                 cin>>name;
                 cin>>marks;
             }
             size(s[i].marks);
         }
         void putsecondlowest(s[].marks,int x);
         void printnames(int);
};

void students :: size(s[].marks) // to sort the array of marks then select second lowest marks i.e. the index[1] marks.
{
    int x=sizeof(s[i].marks[i])/sizeof(s[i].marks[0]);
    putsecondlowest(s[i].marks,x);
}

void students :: putsecondlowest(s[].marks,int x)
{
    sort(s[i].marks,s[i].marks+x)
    printnames(s[1].marks);
}

void students :: printnames(int m)
{
    for(int i=0;i<3;i++)
    {
        if(s[i].marks==m)
        {
            cout<<s[i].name;
        }
    }
}

int main()
{
    students s[3];
    for(int i=0;i<3;i++)
    {
        s[i].getdata();
    }
    return 0;
}
> class students
You need to decide whether this holds
a) A single student.
In which case, it should be called class student, and the array should be in main as student students[3]. All the member functions operate on a single student, and all the loops are in main.

b) All the students.
In which case, you need arrays for all the data members like string name[3]; int marks[3]; and just a single instance of students s; in main. All the member functions operate on arrays, and main just calls the required function.

Use a vector instead of a static array.

Implement a constructor with parameters.

Include algorithm to sort it (by overloading operator <).

Print your result.

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
#include <vector>
#include <algorithm>
#include <string>

//constructor with param
students(string n, int m){
    name=n;
    marks=m;
}

//overload
bool operator<(const student& s){
    return this->mark<student.mark;
}

//declare your array and fill it
vector<students> s;
string name;
int marks;

cin>>name;
cin>>marks;
s.push_back(students(name,marks)); //use of the constructor with parameters

//sorting with algorithm lib
sort(s.begin(),s.end());

cout<<s[1]<<endl;


If there is something that you don't understand, ask.
Last edited on
Thanks Zaap, Salem c, everybody
Topic archived. No new replies allowed.