注意这是转帖,我已经澄清了我的帖子以便更容易理解
void searchArray(char ***array, int count){
char * word = "";
printf("Enter a word: ");
fscanf(stdin, " ");
fscanf(stdin, "%c", &word);
bool found = false;
for(int i = 0; i < count; i++){
if(strcmp(word, (*array)[i]) == 0){
found = true;
break;
}
}
if(found) printf("%s found!\n", word);
else if (!found) printf("%s not found!\n", word);
}
在测试中,代码返回“未找到!”对于每个输入。
上面是我用于搜索和遍历 char 类型数组的代码 ** ...我不确定我的遍历逻辑是否错误或者我是否不正确地使用了 strcmp ...任何帮助将不胜感激!
这是插入代码,可能有助于阐明我到底想做什么:
int insertWord(char **array, int *count, char word[])
{
char *wordPtr;
wordPtr = (char *)malloc((strlen(word) + 1) * sizeof(char));
if (wordPtr == NULL)
{
fprintf(stderr," Malloc of array[%d] failed!\n", *count);
return -1;
}
/* Memory for this word has been allocated, so copy characters
and insert into array */
strcpy(wordPtr, word);
array[*count] = wordPtr;
(*count)++;
return 0;
}
我的任务是在此数据中搜索特定的字符串。
最佳答案
void searchArray(char ***array, int count){
char word[80];
printf("Enter a word: ");
fscanf(stdin, " ");
fscanf(stdin, "%s", word);
bool found = false;
for(int i = 0; i < count; i++){
if(strcmp(word, (*array)[i]) == 0){
found = true;
break;
}
}
if(found) printf("%s found!\n", word);
else if (!found) printf("%s not found!\n", word);
}
此代码完美运行。我认为自从我使用 fscanf(stdin, "%c", &word);它正在读取上一行(缓冲区中)的空白字符,然后搜索它……是这样工作的吗?
谢谢!
关于c - 搜索 char** 类型的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19230145/