samedi 5 décembre 2020

Endless loop with rand() function beacuse of a mutator c++

I have a class Student with a private member that represents a flag. I also have a flag setter function.

#include <iostream>
#include <cstring>


using namespace std;

class Student
{
private:
    string name;
    int flag;
public:
    Student(const string stname)
    :name(stname),flag(0)
    {
        cout << "Student with name " << name << " has been constructed!" << endl;
    };
    ~Student()
    {
        cout << "Student with name " << name << " to be destroyed!" << endl;
    };
    int get_flag();
    void set_flag(const int number);
};

Here are the functions:

void Student::set_flag(const int number){  flag = number;}

int Student::get_flag(){  return flag;}

What i'm trying to do in main is choose a random number to represent the amount of loops and another random number that chooses which of the student objects flags are to be changed.

The code:

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
    string name;
    Student* students[44];
    for(int i=0; i<44; i++)
    {
       cin >> name;
       students[i] = new Student(name);
    }

   int how_many , which;
   srand (time(NULL));
                                //0-44 students can be changed
   how_many = rand() % 44 + 1; //how many students are going to be changed
   int j=1;
   while(j <= how_many) //which students are going to be changed
   {
       //i have 44 students so students array indexes range 0-43
       which = rand() % 43;
       if((students[which])->get_flag() == 1) continue;
       //if the student is not already picked to be changed
       if((students[which])->get_flag() != 1)
       {
          (students[which])->set_flag(1);
          j++;
        }
   }


    for(int i=0; i<44; i++) delete students[i];
}

Why does this result to an endless loop. Genuinely curious. It really looks like i'm doing nothing wrong.

Aucun commentaire:

Enregistrer un commentaire