6.20編寫程序從標準輸入中讀入一些列string對象,知道同一單詞連續出現兩次,或者所有單詞都已讀完,才結束讀取。請使用while循環,每次循環讀取一個單詞。如果連續出現相同的兩個單詞,便以break語句結束,此時,請輸出這個重複的單詞;否則,輸出沒有任何單詞重複的信息。
答案書給的答案(人民郵電出版社):
#include "iostream"
#include "string"
using namespace std;
int main()
{
string preword, curword;
while(cin>>curword)
{
if(curword==preword)
break;
else
preword=curword;
}
if(curword== preword&& !curword.empty())
cout<<"the word' "<<curword<<" ' repeats two times"<<endl;
else
cout<<"there is no word to repeat two times"<<endl;
return 0;
}
但是感覺上總是少了點什麼,運行下發現,當輸入兩個單詞now no時,程序運行錯誤。
重新想了下,終於發現問題,是每次輸入的時候 else preword=curword;錯誤,應該在後面加上一句curword="";
這樣感覺是對的。
不知道到底是我想錯了,還是編輯疏忽了。呵呵