【发布时间】:2020-08-07 06:08:40
【问题描述】:
我有简单的字符串比较例程。最近添加了字符串键盘输入,但是有问题。函数 "cmp("ala", dict);"工作得很好。我怀疑通常与字符串相关的零终止问题,或某些缓冲区长度不兼容。
搜索输入“ala”没有返回任何结果。但是(在注释了不必要的代码之后)这没关系 "cmp("ala", dict);"
这是代码。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char *MyText[256];
char **dictionary()
{
char **dict = (char**)malloc(sizeof(char*) * 5);
int i = 0;
for(i = 0; i < 5; i++)
dict[i] = (char*)malloc(sizeof(char) * 7);
strcpy(dict[0], "mark");
strcpy(dict[1], "ala");
strcpy(dict[2], "wojtek");
strcpy(dict[3], "tom");
strcpy(dict[4], "john");
return (dict);
}
void free_dictionary(char **dict)
{
for (int i = 0; i < 5; i++)
free(dict[i]);
free(dict);
}
int cmp(char *s1, char *s2[5])
{
int i = 0;
int n = 0;
for (i = 0; i < 5; i++)
if (strcmp(s1, s2[i]) == 0) {
n++;
}
if (n > 0)
printf("Found %d", n);
else
printf("Nothing found");
}
int main(int argc, char *argv[])
{
char BufText[255];
int n=0;
char sign;
fflush(stdin);
printf("Give me names: \n");
n = 0;
do {
sign = getchar();
BufText[n ++] = sign;
if(n >= 253) break;
} while (sign !='\n');
BufText [n] = 0;
char **dict = dictionary();
cmp(BufText, dict);
free_dictionary(dict);
return 0;
}
【问题讨论】:
-
“出了点问题”。不要让我们猜测。请准确告诉我们您遇到了什么问题。即给出输入、预期结果和实际结果。
-
抱歉,搜索输入“ala”没有返回任何结果。但是(在注释了不必要的代码之后)这没关系 "cmp("ala", dict);"
-
看起来您正在将
\n存储到BufText中。建议进行基本调试,例如在调试器中运行和/或添加调试打印语句。