Complementary task for topic: 7
M Nemeth · 2023-08-29 15:21:04.625218'
DStrings+Struct: Simple Dictionary 3.
DStrings+Struct: Simple Dictionary 3.
Main goal:
Create a C program that simulates a simple dictionary application. The program should allow the user to add new words and their meanings to the dictionary and search for the meanings of existing words. The word and its meaning will be stored as dynamic strings in a dynamic structure using dynamic memory allocation.
First task:
> Create a search meaning function to find a word in the dictionary that passed to it.
> Try out the function in main
Hint:
Solution
#include
#include
#include
typedef struct {
char* word;
char* meaning;
} DictionaryEntry;
void clearInputBuffer() {
int c;
while ((c = getchar()) != '\n' && c != EOF) {}
}
void addWord(DictionaryEntry** dictionary, int* wordCount) {
DictionaryEntry newWord;
printf("Enter the word: ");
//scanf("%s", &newWord.word); Will not work! try out!
//Dynamic read is complicated
char c=getchar();
int size=1;
char* str=(char*)malloc(size*sizeof(char));
str[0]='\0';
while(c!='\n'){
str=(char*)realloc(str,++size*sizeof(char));
str[size-2]=c;
str[size-1]='\0';
c=getchar();
}
newWord.word=str;
printf("Enter the meaning: ");
//scanf("%s", &newWord.meaning); Will not work! try out!
c=getchar();
size=1;
str=(char*)malloc(size*sizeof(char));
str[0]='\0';
while(c!='\n'){
str=(char*)realloc(str,++size*sizeof(char));
str[size-2]=c;
str[size-1]='\0';
c=getchar();
}
newWord.meaning=str;
(*wordCount)++;
*dictionary = (DictionaryEntry*)realloc(*dictionary, (*wordCount) * sizeof(DictionaryEntry));
(*dictionary)[*wordCount - 1] = newWord;
printf("Word added successfully!\n");
}
void searchMeaning(DictionaryEntry* dictionary, int wordCount, char* searchWord) {
int found = 0;
for (int i = 0; i < wordCount; i++) {
if (strcmp(dictionary[i].word, searchWord) == 0) {
printf("Meaning: %s\n", dictionary[i].meaning);
found = 1;
break;
}
}
if (!found) {
printf("Word %s not found in the dictionary.\n",searchWord);
}
}
int main() {
int wordCount = 0;
DictionaryEntry* dictionary = NULL;
char searchWord[100]; //to read the word...
addWord(&dictionary, &wordCount);
addWord(&dictionary, &wordCount);
printf("Enter the word to search: ");
scanf("%99s", searchWord);
searchMeaning(dictionary, wordCount, searchWord);
for(int i=0;i
Explanation
Just a search