String Comparison Problem

Hello all,

I have the following code:

void Check_Pump_Counter(void)
{
    char datestr[10];   
    DateTime nowtime = RTC.now();

    sprintf(datestr, "%02d:%02d", nowtime.hour(), nowtime.minute());
    Serial.print ("*");
    Serial.print (datestr);
    Serial.println ("*");
    
    if (datestr == "22:06")
    {
      pump_counter = 0;
      debug(1, 2, "Resetting Pump Counter");
    }
}

Problem is that condition if (datestr == "22:06") fails always.

Any advise?

Thank U

Why are you checking the string after using the sprintf function? Why not just test the actual output from the nowtime.hour() and nowtime.minute() functions? You could read them into their own variables, print out the hour and minute and check them like this.

if (hour == 22 && minute == 6)
{
pump_counter = 0;
debug(1, 2, "Resetting Pump Counter");
}

ookid:
Why are you checking the string after using the sprintf function? Why not just test the actual output from the nowtime.hour() and nowtime.minute() functions? You could read them into their own variables, print out the hour and minute and check them like this.

if (hour == 22 && minute == 6)
{
pump_counter = 0;
debug(1, 2, "Resetting Pump Counter");
}

Yes this is better alternative. But I would really like to know why this does not work.
Thanks for the answer ....

You're not comparing strings, you're comparing pointers to blocks of memory that contain strings. It will always be false unless you compare the string with itself.

You should use the function strcmp(a, b) to compare strings. It returns <0 if a is alphabetically less than b, >0 if a is alphabetically greater than b, and 0 if they are the same.

So your comparison should look like:

    if (strcmp(datestr, "22:06") == 0)
    {
      pump_counter = 0;
      debug(1, 2, "Resetting Pump Counter");
    }

majenko:
You're not comparing strings, you're comparing pointers to blocks of memory that contain strings. It will always be false unless you compare the string with itself.

You should use the function strcmp(a, b) to compare strings. It returns <0 if a is alphabetically less than b, >0 if a is alphabetically greater than b, and 0 if they are the same.

So your comparison should look like:

Thank U majenko ...