【问题标题】:my strncmp isnt working for two 2d arrays我的 strncmp 不适用于两个二维数组
【发布时间】:2021-09-30 21:13:45
【问题描述】:

我正在尝试比较并在我的两个数组中查找匹配项,但它不起作用,谁能帮忙?

const char spam[30][30] = {"cash bonus","earn money","fast cash","free access","free gift","free membership",
    "giveaway","million dollars","information you requested","act now","winner","you have been selected",
    "congratulations","lose weight","meet singles","no cost","no interest","social securtiy number","bonus",
    "ad","join millions","opt in","warranty","instant","prize","lowest price","get paid","get out of debt","one time","winning"};
    char resp[SIZE][SIZE];//response string array 
    printf("Enter an email to be checked for spam\n");
    scanf("%s", &resp);
    
    //check if there is a match
    for(int i = 0; i < 30; i++){
        for(int j = 0; j < 30; j++){
        resp[i][j] = tolower(resp[i][j]);//make it lowercase
        int match = strncmp(resp[i], spam[i] );//compare 
        if(match == 0){
            printf("This email is spam! :(\n");
        }else{
            printf("No match :) \n");
        }//if else
    }//for loop2
    }//for loop1

【问题讨论】:

  • scanf("%s", &amp;resp)非常错误。 &amp;resp 的类型是 char (*)[SIZE][SIZE],而不是 %s 格式所期望的 char *。这会导致未定义的行为
  • 我应该用什么来代替 %s?
  • edit 并显示minimal reproducible example。此外,您应该正确格式化您的代码,它非常难以阅读。
  • strncmp 接受三个参数。你的编译器应该抱怨这一点。你可能想要strcmp
  • 你应该使用一个循环来一个一个地读取 30 个字符串。

标签: arrays c char matching strncmp


【解决方案1】:

您无法以这种方式真正实现您的目标。您的垃圾邮件库元素由 2 个以空格分隔的单词组成。但是您的输入只是每个resp[i] 中的一个单词。 (除了使用 scanf() 逐字逐句输入,没有简单的方法可以在 2D 数组中输入。
因此,当您将单个单词 resp[i] 与双单词字符串 cash bonus 进行比较时,它将总是返回 false
Here 是一个指南这可以帮助你。另外,我很想更新这个问题。有没有办法用字符串字典来识别垃圾邮件,比如spam 2D 数组?

【讨论】:

  • 我在这里添加它是因为它对于问题的评论部分来说太长了。
猜你喜欢
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 2020-04-27
  • 1970-01-01
  • 2021-07-15
  • 2022-06-15
  • 2021-11-21
  • 2018-09-19
相关资源
最近更新 更多