Topics: Files, loops, functions, arrays Write a program that repeatedly asks the
ID: 3751461 • Letter: T
Question
Topics: Files, loops, functions, arrays
Write a program that repeatedly asks the user to enter a word. After each word is entered, the program tells the user if the word is correctly spelled or not.
Sample run:
Welcome to the spell checker! Please enter a word:
> apple
The word apple is spelled correctly!
Enter another word:
> snake
The word snake is spelled correctly!
Enter another word:
> compooter
WHOA! compooter isn’t a word! Bad human! Learn to spell!
> dinosore
WHOA! dinosore isn’t a word! Bad human! Learn to spell!
To solve this problem: Download the following text file to your program directory. This file is a dictionary listing ALL THE WORDS IN THE ENGLISH LANGUAGE: largedictionary.txt
This file contains exactly 202,412 words (you may use this number to decide how big to make your array, if you like). A very smart approach is to create a smaller version of the dictionary (say 10 words) for testing to get things working first.
Suggestion: Break the problem down into steps. For example, you might implement the following “pseudo code”:
1)Create a giant array. Read each word in from the dictionary file and store the word in the array.
2)Enter a loop in which you ask the user to enter a word.
a)Check if the word entered is in your giant array of words.
i)If so, congratulate the user.
ii)If not, berate the user for their flawed spelling.
Explanation / Answer
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char dic[10][15];
int main()
{
FILE *file; /* declare a FILE pointer */
int cnt=0,i=0;
char line[20];
char cmp[20];
int len=0;
int success=1;
file = fopen("data.txt", "r"); /* open a text file for reading */
while(fgets(line, sizeof line, file)!=NULL) { /* keep looping until NULL pointer... */
len = strlen(line);
line[len-1]='';
strcpy(dic[cnt],line);
cnt++;
}
while(1) /* keep looping */
{
success =1 ;
printf("Enter Word ");
scanf("%s",cmp);
for(i=0; i<cnt; i++){
if(strcmp(cmp,dic[i])==0){ /* compaire the word */
printf("The word %s is spelled correctly! ",dic[i]);
success = 0;
break;
}
}
if(success != 0)
printf("WHOA! %s isn’t a word! Bad human! Learn to spell! ",cmp);
}
return 0;
}