Reputation: 5470
Note that this is a repost, I have clarified my post to be more understandable
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);
}
In testing, the code returns " not found!" for every input.
The above is the code that I have for searching and traversing an array of type char ** ... I'm not sure whether I have my traversing logic wrong or if I'm improperly using strcmp... Any help would be greatly appreciated!
Here is the code for insertion which may help to clarify what exactly I'm trying to do:
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;
}
My task is to search for a specific string in this data.
Upvotes: 1
Views: 186
Reputation: 5470
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);
}
This code works perfectly. I think that since I was using fscanf(stdin, "%c", &word); it was reading in the open space character from the previous line (in the buffer) and then searching for it...is that how that works?
Thanks!
Upvotes: 1