[英]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
函數將給定的輸入字符串拆分為標記。 它通過修改要標記的字符串來實現這一點,在要搜索的分隔符位置放置一個空字節。
所以在調用strtok
, inputTime
看起來像這樣:
{ '1','2','\0','0','5',':','1','0','P','M','\0' }
一個空字節代替第一個:
。 所以如果你要打印inputTime
你會得到12
,這意味着你不會找到P
。
因為輸入字符串被修改,所以你應該在調用strtok
之前搜索P
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.