首页 > 解决方案 > c编程函数不返回false

问题描述

     #include "ctype.h"
     #include "string.h"
     #include "stdbool.h"
     #include "stdio.h"

   int check_for_sub_string(char s[],char word[])
  {
   int flag = false;
   char mark[]=" ";
   char *tok;
   tok = strtok(s,mark);
   while (tok!=NULL)
   {
    tok= strtok(NULL,mark);
    if (strcmp(tok,word)==0)
    {
        flag= true;
        return flag;
    }
    else flag = false;

   }return flag;
  }

据说,当我使用不在字符串中的单词运行代码时,它不会返回 0。我不知道为什么。例如,我使用 s[]="this is a test string" 和 word[]="kol" 运行它,它不会返回 0。我将返回标志放在循环的末尾,所以如果它没有'找不到返回false的词。

标签: c

解决方案


它不会返回 false 因为它崩溃(或至少调用未定义的行为):当您到达字符串的末尾时,strtok返回 NULL,但您立即将该 NULL 指针传递给strcmp. 直到循环体结束时才进行测试tok != NULL,那为时已晚。


推荐阅读