Question

I've been creating an idle program to count in minutes when the mouse and keyboard are inactive. This is what I have so far:

using namespace std;

while(true)
{
    GetLastInputInfo(&last_info);
    tickCount = GetTickCount();
    int minutes = (tickCount - last_info.dwTime) / 60000;
    count++;

    if((minutes >= 1) && (count%3000==0))
    {
        ifstream in("in.txt");
        ofstream out("out.txt");
        float sum;
        in >> sum;
        sum = sum++;
        out << sum;
        out << in.rdbuf();
        out.close();
        in.close();
    }
    std::cout << "Idle Time: " << minutes << " minutes." << std::endl;
}
}

When I run it idle for one minutes the "sum" says it's 1, I then close the program and open it up for one minutes again and the "sum" says it's 2. I close the program and open it for one more minute and it's back down to 1. Why is this happening?

Was it helpful?

Solution

Here's what i think happens.

contents of in.txt 1

contents of out.txt 2 1 2 1

when you read your value from in into sum, sum = 1; sum++ happens, sum becomes 2.

2 goes into out.txt; then 1 goes into out.txt. then you print "idle time". and it goes round and round and round since sum is always initialized to 1.

try commenting out this line

 out << in.rdbuf();

or declaring sum with a greater scope (outside the file reading loop)

also you never seem to add minutes to it...

EDIT: lets try this...

if((minutes >= 1) && (count%3000==0))
{
    time_t date = time(NULL); //store the time in our date
tm* timePtr = localtime(&t); //now we can extact dates out of it

    int day = timePtr->tm_mday;
    int month = timePtr->tm_mon;
    int year = 1900 + timePtr->tm_year; //trust me, you gotta 1900 to it.
    char* filename;
    sprintf(filename, "log-%d-%d-%d.txt", day, month, year);
    ifstream in(filename);
 //   float sum; why is this float when we do sum++ below?
    int sum;
    in >> sum;
    sum++;
    in.close();
    ofstream out(filename);
    out << sum;
    out.flush();
    out.close();
}

OTHER TIPS

This line is undefined behavior:

sum = sum++;

You can't modify a variable more than once between sequence points. You should just write this instead to increment the sum variable:

sum++;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top