【发布时间】: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", &resp)是非常错误。&resp的类型是char (*)[SIZE][SIZE],而不是%s格式所期望的char *。这会导致未定义的行为。 -
我应该用什么来代替 %s?
-
请edit 并显示minimal reproducible example。此外,您应该正确格式化您的代码,它非常难以阅读。
-
strncmp接受三个参数。你的编译器应该抱怨这一点。你可能想要strcmp。 -
你应该使用一个循环来一个一个地读取 30 个字符串。
标签: arrays c char matching strncmp