मैं अपनी कक्षा के लिए "शब्दकोश" पर काम कर रहा हूं। मैं एक पूर्णांक सरणी NumOfWordsInFile[]
कहा जाता है जहां NumOfWordsInFile[0]
कितने शब्द a.txt में हैं से मेल खाती है और NumOfWordsInFile[25]
Z.txt कोलंबे स्विच स्टेटमेंट से कैसे बचें? सी ++
यह अब जैसा कि मैंने पत्र के 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);
}
आपके पास आपका जवाब है। आप जो चाहते हैं उसे पूरा करने के लिए अक्षर ए-जेड के संगत लेआउट का उपयोग करने पर बहुत अधिक सहमत हैं (अच्छे कारण के लिए)। जब तक आप केवल अंग्रेज़ी वर्णों का उपयोग कर रहे हों (जैसा कि रेडएक्स ने बताया), यह सबसे अच्छा समाधान है। –