[英]Searching type char** for a string
请注意,这是一个转发,我已经澄清了我的帖子更容易理解
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); 它正在从上一行(在缓冲区中)读取空白字符,然后进行搜索...这是如何工作的?
谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.