簡體   English   中英

為什么 strchr 不將程序帶入 if 條件?

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

我正在嘗試運行以下代碼,但在執行過程中,代碼未進入 if 條件。 為什么代碼在運行時不進入 if 條件? 我已經標記了問題條件。

在 Windows 10 上運行這個程序。 線程模型:posix gcc version 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: σ@

strtok函數將給定的輸入字符串拆分為標記。 它通過修改要標記的字符串來實現這一點,在要搜索的分隔符位置放置一個空字節。

所以在調用strtokinputTime看起來像這樣:

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

一個空字節代替第一個: 所以如果你要打印inputTime你會得到12 ,這意味着你不會找到P

因為輸入字符串被修改,所以你應該調用strtok之前搜索P

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM