2010-08-31 222 views
1

我已經開始學習C++,並且正在通過C++ Primer Plus書中的一些練習。練習自學幫助

在第二章的習題5個是:

編寫使用 焦炭和循環的數組在 時間,直到輸入完成的字讀一個字的程序。 然後,程序應該報告輸入的字數 (不包括完成的 )。樣品運行看起來是這樣的:

Enter words (to stop, type the word done): 
anteater birthday category dumpster 
envy finagle geometry done for sure 
You entered a total of 7 words. 

您應該包括CString的頭 文件並使用的strcmp()函數來 進行對比測試。

很難弄明白這一點。這將是容易得多,如果我可以的if語句和邏輯運算符使用,但我只能使用唯一的:

  1. 循環
  2. 關係表達式
  3. 字符數組

分支statments(即如果,case/switch)和邏輯運算符是不允許的。

任何人都可以給我提示,以推動我朝着正確的方向嗎?

編輯:澄清。輸入必須是一個字符串。所以,一個輸入的幾個詞。

+3

如果一本書禁止使用醜陋的柺杖是一回事,但這是禁止你使用你應該用來解決問題的工具。爲什麼不跳過這個練習。 – Potatoswatter 2010-08-31 05:53:49

+3

@Patatoswatter:...或者忽略無意義的限制,而是寫出最明智的代碼,以便產生正確的最終結果。 – 2010-08-31 05:57:15

+0

大聲笑,我在想同樣的事情。幾分鐘後,我質疑這是否是一個很好的鍛鍊問題。 – ShrimpCrackers 2010-08-31 06:01:28

回答

2

編輯來完成:哎呀,規範說要讀入字符數組......我不會麻煩編輯,這真的很愚蠢。 std::string也包含一個char數組!

cin.exceptions(ios::badbit); // avoid using if or && to check error state 

int n; 
string word; 
for (n = 0; cin >> word, strcmp(word.c_str(), "done") != 0; ++ n) ; 

我喜歡

string word; 
int n; 
for (n = 0; cin && (cin >> word, word != "done"); ++n) ; 
1

提示:一個循環也可以作爲一個條件......

2

使用此僞代碼:

while (input != done) 
    do things 
end-while 
0
integer count 
char array input 

count = 0 
read input 
while(input notequal "done") 
count++ 
read input 
done 
print count 
  • input notequal "done"部分可以 可以爲strcmp(input,"done")完成。如果 返回值是0是手段 輸入相同"done"
  • 讀取輸入可以使用cin
+0

這有效,但輸入必須是一個字符串。 – ShrimpCrackers 2010-08-31 06:00:13

0

你應該先定義字符數組一個最大LEN。然後做while while循環就足夠了。你可以用strcmp函數檢查字符串是否相等。這應該沒問題。