连续编程的C++相同字母

问题描述:

我正在尝试使用字符串编写程序,以确定文件中的某个单词是否有连续两个相同的字母。我写了一个函数来进行:连续编程的C++相同字母

bool likeornot(apstring word) 
{ 
for (int i = 0; i < word.length(); i++) 
{ 
    if (toupper(word[i]) != toupper(word[i + 1])) 
     return false; 
} 
return true; 

} 

码主:

while(!fin.eof()) 
{ 
    fin >> word; 
    if (likeornot(word)) 
     cout << "I like " << word << "." << endl; 
    else 
     cout << "I don't like " << word << "." << endl; 
} 
fin.close(); 

这总是返回false,并告诉我,它不喜欢任何的话,如果有人可以帮助我弄清楚为什么那太棒了。

+0

在使用'fin >> word;'之前,您应该测试读取是否成功。 – user2079303 2014-12-03 00:48:01

+0

是的,我有,如果文件没有打开,程序终止。 – imdabes 2014-12-03 00:53:55

+0

即使在打开文件后(例如,达到eof时),读取文件也可能失败。您应该在每次从流中读取之后测试结果。 – user2079303 2014-12-03 01:00:29

更多类似

for (int i = 0; i < word.length() - 1; i++) 
{ 
    if (toupper(word[i]) == toupper(word[i + 1])) 
      return true; 
} 
return false; 
+0

工作完美,非常感谢你! – imdabes 2014-12-03 00:48:25

+0

您可以通过将最后一个读取值保存在寄存器中来进一步微调优化。 :p – BlamKiwi 2014-12-03 00:48:46

变化

for (int i = 0; i < word.length(); i++) 
{ 
    if (toupper(word[i]) != toupper(word[i + 1])) 
     return false; 
} 

for (int i = 0; i < word.length() - 1; i++) 
{ 
    if (toupper(word[i]) != toupper(word[i + 1])) 
     return false; 
} 

你会在字符串之外在循环的最后比较。

你的循环需要以word.length() - 1结尾,而不是word.length(),这个版本总是比较单词的最后一个字符和字符串最后的字符,推测是一个空终止符。

您正在阅读过去字符串的结尾,但你不可能走到这一步,因为这个错误:

if (toupper(word[i]) != toupper(word[i + 1])) 
    return false; 

如果前两个字母不同意,函数返回false