C++ examples for File Stream:Text File
Counting Instances of Each Word in a Text File
#include <iostream> #include <fstream> #include <map> #include <string> typedef std::map<std::string, int> StrIntMap; void countWords(std::istream& in, StrIntMap& words) { std::string s;/* w w w . java 2 s. co m*/ while (in >> s) { ++words[s]; } } int main(int argc, char** argv) { std::ifstream in("main.cpp"); if (!in) exit(EXIT_FAILURE); StrIntMap w; countWords(in, w); for (StrIntMap::iterator p = w.begin(); p != w.end(); ++p) { std::cout << p->first << " occurred " << p->second << " times.\n"; } }