Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ How can i constantly check if a variable changes in a class?

So, I’ve started programming classes last year. I would like to know how i can make a function in a class that lets me check if a variable has reached a certain threshold and then modify it.
I tried this but i think it just stops at the cycle and never resumes.
It is public and i call it through the main.

This is what I’ve tried so far:

class Numbers{
private: 
    int Limit, Current, counter;

public:
 
        void addCurrent(int a) { Current += a; }
        int getCurrent() {return Current; }
        int getLimit() {return Limit; }
        int getCounter() {return counter; }
         

    void Check() {
        while (true) {
            if (Current >= Limit) {
                counter++;
                Current -= Limit; 
                Limit = Limit * counter;
            }
        }
    }
};

I call it in the main like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include <iostream>
using namespace std;

int main(){
    Numbers.one;
    one.Check();
    one.addCurrent(200);
    cout<< one.getLimit() << "/" << one.getCurrent() << "/" << one.getCounter();
}

Since I’m at a really beginner level I would like to keep it simple, but any help is appriciated.
Thanks

>Solution :

You put your logic into addCurrent:

class Numbers{
private: 
    int Limit = 1;
    int Current = 0;
    int counter = 0;

public:

    void addCurrent(int a) {
        Current += a;
        Check();
    }
    int getCurrent() {return Current; }
    int getLimit() {return Limit; }
    int getCounter() {return counter; }

    void Check() {
        while (Current >= Limit) {
            counter++;
            Current -= Limit; 
            Limit = Limit * counter;
        }
    }
};

int main(){
    Numbers one;
    one.addCurrent(200);
    cout<< one.getLimit() << "/" << one.getCurrent() << "/" << one.getCounter();
}

Demo

Note that I had to make some assumptions about what behavior you want and what values Limit, Current, and counter should have initially. It’s also not clear if you want the Check logic to continue until Current < Limit or if you want it applied once.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading