user2142053
user2142053

Reputation: 21

Parsing words in C; Translating program

I'm developing a program that will translate a string from the user (English) into Spanish. For the assignment I'm given a file that contains a list of a 100 words and their spanish equivalent. I've successfully opened that file, and fed it to the string with a two dimensional array.

What I'm having difficulty with is parsing the words so it will allow me to find the equivalent version of the given words; any words that aren't given are suppose to be replaced with asterisks (*). Any ideas on how I can parse the words from the users inputted string? Below is snippits of the source code to save some time.

--Thanks

char readFile[100][25];

fp = fopen("words.dat", "r");

if (fp == NULL){
   printf ("File failed to load\n");
}

//This is how I stored the file into the two dimensional string.
while (fgets(readFile, 100, fp)){
   x++;
}

printf ("User please input string\n");
gets (input);

That's as far as I've gotten. I commented out the for-loop that outputs the words so I can see the words (for the sake of curiousity) and it was successful. The format of the file string is (english word), (spanish word).

Upvotes: 0

Views: 426

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409356

First of, the array you declare is 100 arrays of 25-character arrays. If we talk about "lines" it means you have 100 lines where each line can be 24 characters (remember we need one extra for the terminating '\0' character). If you want 25 lines of 99 characters each, switch place of the sizes.

Secondly, you overwrite the same bytes of the array over and over again. And since each sub-array is actually only 25 characters, you can overwrite up to four of those arrays with that fgets call.

I suggest something like this instead:

size_t count = 0;
for (int i = 0; i < sizeof(readFile) / sizeof(readFile[0]) &&
                fgets(readFile[i], sizeof(readFile[i]), fp); i++, count++)
{
}

This will make sure you don't read more than you can store, and automatically reads into the correct "line" in the array. After the loop count will contain the number of lines you read.

Upvotes: 2

Related Questions