[英]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.