简体   繁体   English

为什么 strchr 不将程序带入 if 条件?

[英]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.我正在尝试运行以下代码,但在执行过程中,代码未进入 if 条件。 Why does the code not enter the if condition during runtime?为什么代码在运行时不进入 if 条件? I have marked the problem condition.我已经标记了问题条件。

Running this program on Windows 10. Thread model: posix gcc version 5.1.0 (tdm64-1)在 Windows 10 上运行这个程序。 线程模型: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.我尝试使用三元运算符和带有不同字符串的 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);

}

The above code gives me this output: C:\\Users\\XX\\Documents\\Tests\\c-programming>a.exe上面的代码给了我这个输出:C:\\Users\\XX\\Documents\\Tests\\c-programming>a.exe


Found w发现 w
True真的
tempStr: σ@ tempStr: σ@

The strtok function splits the given input string into tokens. strtok函数将给定的输入字符串拆分为标记。 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:所以在调用strtokinputTime看起来像这样:

{ '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 .所以如果你要打印inputTime你会得到12 ,这意味着你不会找到P

Because the input string is modified, you should search for P before calling strtok .因为输入字符串被修改,所以你应该调用strtok之前搜索P

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM