Search code examples
cstringstrchr

Why does the strchr not take the program into an if condition?


I am trying to run the following code, but during execution, the code does not go into the if condition. Why does the code not enter the if condition during runtime? I have marked the problem condition.

Running this program on Windows 10. Thread model: posix gcc version 5.1.0 (tdm64-1)

I have tried using the ternary operator and the if statement with a different string, and strchr works fine in that case.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void main() {

    static char str[] = "hello world";
    static char inputTime[] = "12:05:10PM";
    char *result = strchr(str, 'w');
    long int tempNum = 0;
    char *token, tempStr[10], delimit[] = ":";

    if (strchr(str, 'w'))
        printf("\nFound w");
    else
        printf("\nDid not find w");

    (strchr(inputTime, 'P')) ? printf("\nTrue") : printf("\nFalse");

    token = strtok(inputTime, delimit);

    if (strchr(inputTime, 'P')) {
        printf("Found PM\n");
        tempNum = strtol(token, NULL, 10);
        if (tempNum != 12) 
            tempNum += 12;
        sprintf(tempStr, "%lu", tempNum);
    }
    printf("\ntempStr: %s", tempStr);

}

The above code gives me this output: C:\Users\XX\Documents\Tests\c-programming>a.exe


Found w
True
tempStr: σ@


Solution

  • The strtok function splits the given input string into tokens. It does this by modifying the string to tokenize, placing a null byte in place of the delimiter to search for.

    So after the call to strtok, inputTime looks like this:

    { '1','2','\0','0','5',':','1','0','P','M','\0' }
    

    A null byte is put in place of the first :. So if you were to print inputTime you would get 12, meaning you won't find a P.

    Because the input string is modified, you should search for P before calling strtok.