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);
}
嘗試'而(在>> C)的''而不是同時(在)'? – Bill