1

我正在尝试运行以下代码,但在执行过程中,代码不会进入 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
True
tempStr: σ@

4

1 回答 1

1

strtok函数将给定的输入字符串拆分为标记。它通过修改要标记化的字符串、放置一个空字节来代替要搜索的分隔符来做到这一点。

所以在调用 之后strtokinputTime看起来像这样:

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

一个空字节代替第一个:。因此,如果您要打印,inputTime您会得到12,这意味着您将找不到P.

因为输入字符串被修改了,调用P 应该先搜索一下strtok

于 2019-02-03T15:05:31.117 回答