【发布时间】:2018-01-24 16:55:21
【问题描述】:
所以我应该编写一个 Soundex 转换器代码并打印文件中的行,如果其中一个单词与输入具有相同的 Soundex 代码。我成功地为 Soundex 转换编写了一个函数,但我停留在比较部分。抱歉,如果这听起来微不足道,但是当我逐行比较单词时,strcmp 似乎每次都失败。这是代码...抱歉,如果它太长了
#include<string.h>
#include<ctype.h>
#include<stdio.h>
#include<stdlib.h>
char *soundex(char *s,char* name)
{
int si = 1;
char c;
//char *s = (char *)malloc(1000);
// ABCDEFGHIJKLMNOPQRSTUVWXYZ
char mappings[] = "01230120022455012623010202";
s[0] = toupper(name[0]);
for(int i = 1, l = strlen(name); i < l; i++)
{
c = toupper(name[i]) - 65;
if(c >= 0 && c <= 25)
{
if(mappings[c] != '0')
{
if(mappings[c] != s[si-1])
{
s[si] = mappings[c];
si++;
}
if(si > 3)
{
break;
}
}
}
}
if(si <= 3)
{
while(si <= 3)
{
s[si] = '0';
si++;
}
}
//printf("%s\n",s);
return s;
}
void search(char line[10000],char str[1000])
{
int i,j=0;
char test[1000];
char s[1000];
char b[1000];
for(i=0;line[i] != '\0';i++)
{
if(line[i] == ' ')
continue;
test[j] = line[i];
j++;
if(line[i+1] == ' ' || line[i+1] == '\0')
{
//soundex(test);
test[j] = '\0';
if(strcmp(soundex(s,test),soundex(b,str)) == 0);
{
printf("%s\n",soundex(s,test));
printf("%s\n",soundex(b,str));
printf("%s",line);
break;
}
j = 0;
memset(test,0,strlen(test));
}
}
}
int main()
{
char a[1000],f[1000];
char s[1000];
gets(a);
//soundex(s,a);
//printf("%s",s);
scanf("%s",f);
FILE *fp=fopen(f,"r");
if(fp==NULL)
{
printf("File doesnot exist bro");
}
else
{
long long linenum=1;
char line[10000];
while(fgets(line,10000,fp)!=NULL) //Or fscanf
{
search(line,a);
//printf("%s",line);
linenum++;
}
}
fclose(fp);
}
搜索功能中的 strcmp 命令会出现问题,因为即使结果不同,它也会打印行。我什至会在之后打印比较结果来确定。任何潜在客户都会受到重视。再次对长代码感到抱歉。
【问题讨论】:
-
这是一个需要先调试解决的问题。尝试调试它,如果卡住了再回来。
-
此代码也出现编译器警告,请先修复这些警告。 ` test[j] == '\0';` for 1
-
请edit你的问题告诉我们你做了什么样的调试。我希望您已经在 Valgrind 或类似的检查器中运行了您的minimal reproducible example,并使用诸如 GDB 之类的调试器进行了调查。确保您也启用了全套编译器警告。这些工具告诉了你什么,它们缺少什么信息?并阅读 Eric Lippert 的 How to debug small programs。