我正在为我的班级学习一本“字典”。我有一个int数组称为NumOfWordsInFile[]
其中NumOfWordsInFile[0]
相当于多少字是A.TXT和NumOfWordsInFile[25]
对应Z.txt如何避免长时间切换语句? C++
因为它是现在我有字母的26种不同的条件下一个巨大的开关。我有一个叫AddWord(string word)
的函数。 AddWord获取传递给它的单词的第一个字母并将其插入到相应的.txt文件中。现在是这个问题。每次将一个单词添加到A.txt时,我必须将NumOfWordsInFile[0]
增加1.我能想到的唯一方法就是使用这些巨大的开关。我也有一个deleteWord函数,如果这个单词被删除,反过来会减少NumOfWordsInFile[]
。现在我不想有两个26案例切换,但问题是我不知道如何做到这一点。现在,我可以为删除功能做同样的事情,但我真的不想有数百行更多的代码行。有一个更好的方法吗?
样品在AddWord
功能开关的:
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);
}
你有你的答案。几乎所有人都同意(出于很好的理由)使用字母a-z的连续布局来实现你想要的。只要你只使用英文字符(就像RedX指出的那样),这是最好的解决方案。 – 2011-04-03 23:22:29