c - 如何正确执行 strcmp?

标签 c arrays string strcmp getchar

我必须将字符串“death”与文本文件中的任意五个字符的字符串进行比较。

我似乎无法让我的功能正常工作,但我看不出我做错了什么。有人有什么建议吗?

*注意:我的 strcmp 只返回 -1 或 1 但从不返回 0

#include <stdio.h>
#include <stdbool.h>
#include <string.h>

//Function to check if strings are a match regardless of case
bool doesMatch (char testText[], char testDeath[]) {
 if (strcasecmp(testDeath, testText) == 0) {
      return true;
 }
 else
      return false;
}

int main (int argc, char *argv[]) {
 char test1[5] = {getchar(), getchar(), getchar(), getchar(), getchar()};
 bool testMatch;
 char test2[5] = {'d','e','a','t','h'};

 //Test arrays until End of FIle
 while (test1[4] != EOF) {

      testMatch = doesMatch(test1, test2);
      if (testMatch == true) {
           printf ("Match!\n");
      }

      //"slide" array down one character
      test1[0] = test1[1];
      test1[1] = test1[2];
      test1[2] = test1[3];
      test1[3] = test1[4];
      test1[4] = getchar();

 }

 return 0;
}

最佳答案

正如 Havenard 所说,strcmp() 需要以 null 结尾的字符串,这意味着每个字符串都需要以字符 '\0' 结尾。如果您坚持自己将字符串拼凑在一起,则必须记住在每个字符串的末尾附加空字符,以便对它们执行字符串函数。

关于c - 如何正确执行 strcmp?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15824490/

相关文章:

c - 优化我自己的atoi

紧凑访问嵌套结构中的变量

c - 为什么不能定义大于300*300的二维数组?

没有名称的 C++11 STL 容器数组

javascript - 如何在 JavaScript 中使用运算符 "^"?

C - 高效编码字符串生成算法

c - 请求用户输入二维数组并将数据存储在 C 数组中

c - 在 Windows 中轮询 CTS 线路的状态

php - 将txt文件读入二维数组

java - split 方法在从文件读取时输出值在彼此之下