'How do I write a function to display the student's record of the entered roll number

We have to ask for info(roll no, name, course) of the students from the user. And display the input info. And lastly, have to add another function to ask for roll no. And that entered roll no's student info will be displayed. I am having trouble understanding how to solve the last part.

This is the code I did. I tried other ways but the code won't work.

#include <iostream>

using namespace std;

class Student{

    private:
        int rno ;
        string name ;
        string course ;
    public:
        Student(){
            // default
        }
        Student(int rno, string name, string course){
            this -> rno = rno;
            this -> name = name; 
            this -> course = course;
        }
        void displayMembers(){
            cout << "RNO : " << rno << "\tName : " << name << "\tCourse : " << course << endl;
        }
        // void searchRoll(){
        //     this -> rno = rno;
        // }
};

int main(){

    Student stu[2];
    int rno ;
    string name ;
    string course ;

    // ask info
    for(int i = 0; i < 2; i++){
        cout << "Enter Roll Number : " ;
        cin >> rno;
        cin.ignore();
        cout << "Enter Name : " ;
        getline(cin, name);
        cout << "Enter Course Name : " ;
        getline(cin, course);
        stu[i] = Student(rno, name, course);
    }

    // display
    cout << "Enter Student Informations!" << endl;
    for(int i = 0; i < 2; i++){
        stu[i].displayMembers();
    }

    // search by rno
    // cout << "Enter Roll Number to Search : " ;
    // cin >> rno;
    // for(int i = 0; i < 2; i++){
    //     stu[i].searchRoll();
    // }

    return 0;
}
c++


Solution 1:[1]

You don't want a searchRoll() function in your Student class. You will want to add a getter for the rno member. Then, you could simply loop through the array and compare the entered value to the rno member of each item and stop when you get a match.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jim Rhodes