2014-12-03 44 views
0

我正在嘗試使用字符串編寫程序,以確定文件中的某個單詞是否有連續兩個相同的字母。我寫了一個函數來進行:連續編程的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

回答

1

更多類似

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

1

變化

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; 
} 

你會在字符串之外在循環的最後比較。

0

你的循環需要以word.length() - 1結尾,而不是word.length(),這個版本總是比較單詞的最後一個字符和字符串最後的字符,推測是一個空終止符。

0

您正在閱讀過去字符串的結尾,但你不可能走到這一步,因爲這個錯誤:

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

如果前兩個字母不同意,函數返回false