'Dictionary Output in C
I am trying to design a make-believe dictionary translator. The first section of input is the entries themselves, followed by an empty line, followed by the foreign word. The Output will be whatever the foreign words matching English word is, or "eh" if there is no match.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
struct dictionaryEntry {
char english[20];
char foreign[20];
};
int CREATE_LIST(struct dictionaryEntry *list) {
char buffer[50];
int counter = 0;
//fgets is necessary to detect newline
if ((fgets(buffer, 20, stdin) == NULL))
exit(0);
while (buffer[0] != '\n') {
char english[20], foreign[20];
sscanf(buffer, "%s %s", english, foreign);
//Words put into list
strcpy(list[counter].english, english);
strcpy(list[counter].foreign, foreign);
//End of while loop so while loop can detect it
if ((fgets(buffer, 20, stdin) == NULL))
exit(0);
counter++;
}
return counter;
}
//Performs a linear search through array struct
void SEARCH(struct dictionaryEntry *list, int lineCount) {
char userInput[50], buffer[50];
int i = 0;
bool flag = false;
if ((fgets(buffer, 20, stdin) == NULL))
exit(0);
//Check to make sure no newline
while(buffer[0] != '\n') {
flag = false; //Resets
//Loops through entire array for word
for(i = 0; i<lineCount; i++) {
sscanf(buffer, "%s", userInput);
//If match is found, displays English word and set flag to true
if(strcmp(list[i].foreign, userInput) == 0){
printf("%s\n", list[i].english);
flag = true;
}
}
//If flag is false, then match was not found; print 'eh'
if(flag == false)
printf("%s", "eh\n");
if ((fgets(buffer, 20, stdin) == NULL))
exit(0);
}
}
int main(void) {
int lineCount = 0;
struct dictionaryEntry *list = malloc(lineCount * sizeof(struct dictionaryEntry));
lineCount = CREATE_LIST(list);
SEARCH(list, lineCount);
for(int i = 0; i<lineCount; i++) {
printf("English: %s\nForeign: %s\n", list[i].english, list[i].foreign);
}
free(list);
return 0;
}
When I use this Input:
dog ogday
cat atcay
pig igpay
froot ootfray
loops oopslay
The second index seems to change by the time it reaches the final print statement in main. This is the new Output:
English: dog
Foreign: ogday
English: pslay
Foreign: atcay
English: pig
Foreign: igpay
English: froot
Foreign: ootfray
English: loops
Foreign: oopslay
How can I fix this Output to match correctly?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
