2010-03-10 83 views
0

我寫了一個函數來計算元音。如果在流末尾有元音,它會被計數兩次。爲什麼?istream結束時未檢測到

#include <iostream> 
#include <string> 
#include <map> 
using namespace std; 

void countChars(istream& in, string theChars, ostream& out) { 
    map<char, int> charMap; 
    map<char, int>::iterator mapIt; 

    for (string::iterator i = theChars.begin(); i != theChars.end(); ++i) { 
    charMap[*i] = 0; 
    } 
    while (in) { 
    char c; 
    in >> c; 
    c = tolower(c); 
    if (charMap.count(c)) 
     ++charMap[c]; 
    } 
    for (mapIt = charMap.begin(); mapIt != charMap.end(); ++mapIt) { 
    out << (*mapIt).first << ":" << (*mapIt).second << endl; 
    } 
} 

int main(int argc, char **argv) { 
    std::string s = "aeiou"; 
    countChars(std::cin, s, std::cout); 
} 
+2

嘗試'而(在>> C)的''而不是同時(在)'? – Bill

回答

4

因爲當最後讀取失敗,原因是用光數據的in評估爲假,不是因爲下一個讀會失敗的原因用完數據。它不會「向前看」,它只知道流如果已經嘗試過並且無法讀取就完成了。

所以會發生以下情況:

  • 最後一個字符讀取並處理
  • in評估爲真,所以循環重複
  • 嘗試再次讀取,但是沒有更多的數據,所以c未被修改
  • 通過未定義(雖然並不令人驚訝)的行爲,c恰巧包含它在循環的最後一次運行中的值
  • 因此,您處理同樣的字符再次。

你應該寫:

char c; 
while (in >> c) { etc } 
+1

+1,更徹底! – Bill