我编写了一个函数来搜索数组中的char,如果找到则返回其后继,否则返回-1。然后,如果单词以元音结尾,则算法会添加辅音,反之亦然。
即使使用文件的最后一个单词,此代码也能正常运行:
changedChar = cipherChar(character, consonants, tConsonants);
if (changedChar != -1) charType = 'c';
else {
changedChar = cipherChar(character, CONSONANTS, tConsonants);
if (changedChar != -1) charType = 'c';
else {
changedChar = cipherChar(character, vowels, tVowels);
if (changedChar != -1) charType = 'v';
else {
changedChar = cipherChar(character, VOWELS, tVowels);
if (changedChar != -1) charType = 'v';
else {
changedChar = cipherChar(character, others, tOthers);
if (changedChar != -1) charType = 'o';
else {
changedChar = changeDigit(character);
if (changedChar != -1) charType = 'o';
else {
changedChar = cipherChar(character, punctuation, tPunctuation);
if (changedChar != -1) charType = 'o';
}
}
}
}
}
}
if (changedChar != -1) outFile << changedChar;
if (searchChar(inFile.peek(), punctuation, tPunctuation) > -1)
if (charType == 'v') {
outFile << consonants[nVowel];
nVowel < 4 ? nVowel++ : nVowel = 0;
}
else if (charType == 'c') {
outFile << vowels[nConsonant];
nConsonant < 20 ? nConsonant++ : nConsonant = 0;
}
但是这个其他人不会在文件的最后一个字后添加一个额外的字母:
charType = 'c';
changedChar = cipherChar(character, consonants, tConsonants);
if (changedChar == -1) {
changedChar = cipherChar(character, CONSONANTS, tConsonants);
if (changedChar == -1) {
charType = 'v';
changedChar = cipherChar(character, vowels, tVowels);
if (changedChar == -1) {
changedChar = cipherChar(character, VOWELS, tVowels);
if (changedChar == -1) {
charType = 'o';
changedChar = cipherChar(character, others, tOthers);
if (changedChar == -1) {
changedChar = changeDigit(character);
if (changedChar == -1) changedChar = cipherChar(character, punctuation, tPunctuation);
}
}
}
}
}
if (changedChar != -1) outFile << changedChar;
if (searchChar(inFile.peek(), punctuation, tPunctuation) > -1)
if (charType == 'v') {
outFile << consonants[nVowel];
nVowel < 4 ? nVowel++ : nVowel = 0;
}
else if (charType == 'c') {
outFile << vowels[nConsonant];
nConsonant < 20 ? nConsonant++ : nConsonant = 0;
}
为什么呢?我真的很困惑。
答案 0 :(得分:6)
如果逻辑中有这么多if条件,那么功能设计中应该存在一个缺陷。正确理解您的要求并尝试简化逻辑。
答案 1 :(得分:3)
我看到的唯一区别是,如果没有找到任何内容,则在第二段代码中charType
具有值'o'
,而在第一段代码中如果没有找到则{{1}在此代码运行之前,它具有任何初始值(您尚未向我们展示)。
除此之外,这两段代码在语义上是相同的,所以如果这不是问题的原因,那么问题在于你没有向我们展示的代码。