为什么strchr不能使程序进入if条件?

时间:2019-02-03 14:40:59

标签: c string strchr

我正在尝试运行以下代码,但是在执行期间,该代码不会进入if条件。 为什么代码在运行时未输入if条件?我已经标记了问题情况。

在Windows 10上运行此程序。 螺纹型号:posix gcc版本5.1.0(tdm64-1)

我尝试使用三元运算符和带有不同字符串的if语句,并且在这种情况下strchr可以正常工作。

#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);

}

上面的代码给了我这个输出: C:\ Users \ XX \ Documents \ Tests \ c-programming> a.exe


找到w
真实
tempStr:σ@

1 个答案:

答案 0 :(得分:1)

HttpRequests.get(codePoint: "getCategoryList") { (category: Category?) -> Void in ... } 函数将给定的输入字符串拆分为标记。通过修改字符串以进行标记来实现此目的,将空字节替换为要搜索的定界符。

因此,在调用strtok之后,strtok如下所示:

inputTime

空字节代替第一个{ '1','2','\0','0','5',':','1','0','P','M','\0' } 。因此,如果您要打印:,则会得到inputTime,这意味着您将找不到12

由于修改了输入字符串,因此应在调用P之前搜索P