[問題] strcmp比對字串

看板C_and_CPP作者 (janus)時間13年前 (2011/03/21 23:47), 編輯推噓0(008)
留言8則, 2人參與, 最新討論串1/1
開發平台(Platform): vs2005 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): 我的想法是讀取字元,然後按下enter鍵 再把字元存入陣列中 只要碰到空白字元count就會+1,用來代表前面有幾個的單字 (ex:apple boy<enter>,count會等於1) 並更新陣列的索引i,讓空白後面的字元繼續從inbox[0]開始存。 接著我想知道在我做完每一組字串陣列,是否有出現"done"字串 不過似乎一直進不去if條件式,請問是否有哪裡有漏洞?!! 餵入的資料(Input):practice make perfect done haha<enter> 預期的正確結果(Expected Output): 應該會執行cout << "\n!!!";來表示有讀取到"done" 錯誤結果(Wrong Output): 只有出現每一組字串陣列,並沒有顯示有比對到"done" 程式碼(Code): http://codepad.org/xPnZWsea #include<iostream> #include<cstring> int main() { using namespace std; int ch; int count=0; char inbox[60]; char str[5]="done"; int i=0; cout << "Enter words (to stop, type the word done):\n"; while( (ch = cin.get())!=EOF ) { if(ch == ' ') { ++count; inbox[i]='\0'; if(strcmp(inbox,str)==0) { cout << "\n!!!"; } cout << "\n#inSide: " << inbox << endl; i=0; } inbox[i++]=ch; } inbox[i]='\0'; cout << "#outSide: " <<inbox; cout << count << " characters\n"; system("pause"); return 0; } 補充說明(Supplement): 這是C++ Primer Plus 5/e,第五章程式練習的第7題 沒想到在這裡卡好久= =" -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 111.243.58.80 ※ 編輯: janusliu 來自: 111.243.58.80 (03/21 23:48) ※ 編輯: janusliu 來自: 111.243.58.80 (03/21 23:49)

03/21 23:57, , 1F
你的程式會連 done 前面那個空白也吃進去
03/21 23:57, 1F

03/21 23:57, , 2F
你試試看把 done 擺在第一個
03/21 23:57, 2F

03/22 01:07, , 3F
題目是輸入一堆單字,要求計算done之前有幾個單字,所以
03/22 01:07, 3F

03/22 01:08, , 4F
應該是不能第一個就放done吧~這樣就沒意義了
03/22 01:08, 4F

03/22 01:09, , 5F
我的意思是,如果你輸入的是「xxxx done」
03/22 01:09, 5F

03/22 01:09, , 6F
第一次inbox是「xxxx」,第二次是「 done」
03/22 01:09, 6F

03/22 01:09, , 7F
「 done」前面會多一個空格,跟「done」比較永遠不會成立
03/22 01:09, 7F

03/22 12:09, , 8F
喔喔喔~了解~我改看看~感謝@@
03/22 12:09, 8F
文章代碼(AID): #1DXtC2ch (C_and_CPP)