NumOfWordsInFile[]
的int数组,其中NumOfWordsInFile[0]
对应于A.txt中的单词数,NumOfWordsInFile[25]
对应于Z.txt中的单词数。目前,我有一个巨大的switch语句处理26个不同字母的情况。我有一个名为
AddWord(string word)
的函数。AddWord获取传递给它的单词的第一个字母,并将其插入到相应的.txt文件中。现在问题来了,每次添加单词到A.txt时,我必须将NumOfWordsInFile[0]
增加1。我能想到的唯一方法是使用这些巨大的switch语句。如果要删除单词,则相反地递减NumOfWordsInFile[]
。现在,我不想有两个26个case的switch语句,但问题是我不知道还有其他方法。现在我可以为删除功能做同样的事情,但我真的不想再增加数百行代码。有更好的方法吗?
AddWord
函数中的switch示例:case 'w':
if (numOfWordsInFile[22] < maxWordsPerFile) {
fout.open(fileName.data(), ios::app);
fout << word << " " << endl;
numOfWordsInFile[22]++;
if (totalWordsInDict < maxWordsInDict) {
totalWordsInDict++;
}
return(Dictionary::success);
} else {
return(Dictionary::failure);
}
case 'x':
if (numOfWordsInFile[23] < maxWordsPerFile) {
fout.open(fileName.data(),ios::app);
fout << word << " " << endl;
numOfWordsInFile[23]++;
if (totalWordsInDict < maxWordsInDict) {
totalWordsInDict++;
}
return(Dictionary::success);
} else {
return(Dictionary::failure);
}
删除功能。
bool Dictionary::DeleteAWord(string word)
{
ofstream fout;
ifstream fin;
string x;
string fileName="#.txt";
int count=0;
vector <string> words;
bool deleted=false;
fileName[0]=toupper(word[0]);
fin.open(fileName.data()); //makes the file depending on the first letter of the argument "word"
while (fin >> x)
{
words.push_back(x);
count++;//number of elements in vector
}
if (SearchForWord(x))
{
for ( ;count > 0; count--)
{
if (words[count-1] == word)
{
// cout << "Found word " << word << " during search, now deleting" << endl;
words.erase(words.begin()+(count-1));
deleted = true;
/*
This clearly doesn't work and is what I need help with, I know why it
doesn't work but I don't know how to make it better than having another
huge switch.
*/
numOfWordsInFile[toupper(word[0])]--;
/*
*/
totalWordsInDict--;
fin.close();
}
}
if (deleted)
{
fout.open(fileName.data());
for (int i = 0; i < words.size(); i++)
fout << words[i] << endl;
return(Dictionary::success);
}
return(Dictionary::failure);
}
return(Dictionary::failure);
}