📄 pex14_6.cpp
字号:
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
#include <ctype.h>
#pragma hdrstop
#include "hash.h"
#include "strclass.h"
// extract a word beginning with a letter and possibly
// other letters/digits
int GetWord (ifstream& fin, char w[])
{
char c;
int i = 0;
// skip non-alphabetic input
while ( fin.get(c) && !isalpha(c));
// return 0 on end of file
if (fin.eof())
return 0;
// record 1st letter of the word
w[i++] = c;
// collect letters and digits. NULL terminate
while (fin.get(c) && (isalpha(c) || isdigit(c)))
w[i++] = c;
w[i] = '\0';
return 1;
}
// function for use by the Hash class
unsigned long hash(String s)
{
unsigned long hashval = 0;
// shift hashval left three bits and add in next character
for(int i=0;i< s.Length();i++)
hashval = (hashval << 3) + s[i];
return hashval;
}
// translate each uppercase character of s
// to lower case
void Lowercase(String& s)
{
for(int i=0;i < s.Length();i++)
if (isupper(s[i]))
s[i] = tolower(s[i]);
}
void main(void)
{
// hash table for words
HashTable<String> HT(1001,hash);
// used to initialize hash table and read document
ifstream fin;
char s[50];
String str;
int misspelled = 0;
// open "words"
fin.open("words", ios::in | ios::nocreate);
if (!fin)
{
cerr << "Cannot open \"words\"" << endl;
exit(1);
}
// insert each word from the file "words" into the
// hash table. this is the database containing
// "correctly spelled" words
while(fin >> str)
HT.Insert(str);
fin.close();
// open the document
cout << "Enter the name of the document: ";
cin >> s;
fin.open(s, ios::in | ios::nocreate);
if (!fin)
{
cerr << "Cannot open " << s << endl;
exit(1);
}
// read through the document and check spelling
while(GetWord(fin,s))
{
// str is String object having value of C++ string s
str = s;
// convert str to lowercase
Lowercase(str);
// look str up the the hash table
if (!HT.Find(str))
{
// output misspelled word message once
if (misspelled == 0)
{
cout << endl << "Misspelled words:" << endl << endl;
misspelled = 1;
}
// output original word s
cout << s << endl;
}
}
}
/*
<Run>
<File "pex14_6.dat">
She and her friend went
to school.
<Run>
Enter the name of the document: pex14_6.dat
Misspelled words:
went
*/
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -