/* spellchk.cpp - Matt Mahoney, mmahoney@cs.fit.edu This program takes 2 file name arguments. It prints any word that occurs in the first file but not in the second, along with the line number. If the second file is a dictionary, then the program acts as a spell checker. A word is any sequence of letters and no other characters. For example, "It's" is 2 words, "it" and "s". Comparison is not case sensitive. The first line is 1. For example, if file1 and file2 are as follows: file1: This is file 1. file2: THIS is the OTHER-file... The program runs as follows: spellchk file1 file2 (no output) spellchk file2 file1 1: the 2: OTHER spellchk file1 file1 (no output) The program prints an error message if there are not exactly 2 file name arguments or if either file cannot be read. */ #include #include #include #include #include using namespace std; // Return string s with all upper case letters converted to lower case string lowercase(string s) { for (string::iterator p=s.begin(); p!=s.end(); ++p) { if (isupper(*p)) *p = tolower(*p); } return s; } // Print words in file argv[1] that are not in argv[2] int main(int argc, char** argv) { // Check for 2 file names if (argc!=3) { cout << "Usage: spellchk test_file dictionary_file\n"; return 1; } // Open files, exit on failure ifstream f1(argv[1]), f2(argv[2]); if (!f1) cout << "File " << argv[1] << " not found\n"; if (!f2) cout << "File " << argv[2] << " not found\n"; if (!f1 || !f2) return 1; // Store lower case words from file f2 in dict map dict; // dict[word] is true if word is read from f2 string s; // current word char c; while (f2.get(c)) { if (isalpha(c)) s+=c; else if (s!="") { dict[lowercase(s)]=true; s=""; } } // Test words in file f1. Print "line: word" if not in dict. s=""; int line=1; // Line number in f1 while (f1.get(c)) { if (isalpha(c)) s+=c; else if (s!="") { if (!dict[lowercase(s)]) cout << line << ": " << s << "\n"; s=""; } if (c=='\n') ++line; } return 0; }