Hi!
I'm trying to count the number of occurrences of each word in a text file. But program put in the file the first symbol of inputed word only (line 34) and don't enter in the for-statement (line 51). What should I serach for in my code in order to find the problem?
Thanks in advance.
#include <fstream.h>
#include <iostream.h>
#include <map.h>
#include <string>
#include <iterator>
#include <cstdlib>
#include <iomanip>
#include <conio.h>
typedef std::map<std::string, int> StrIntMap; // map for counting
void countWords(std::istream& in, StrIntMap& words) // func that count words
{
std::string s;
while (in >> s)
{
++words[s];
}
}
using namespace std;
int main ()
{
char str [80];
ofstream out("test.dat");
if(!out) {
cout << "Cannot open file.\n";
return 1;
}
do {
cout << "Enter a word (BL to quit):\n";
cin >> str;
out << str;
} while(*str != '\n'); // if empty str inputed -> stop do-while
out.close();
ifstream in("test.dat");
if(!in) {
cout << "Cannot find file.\n";
return 1;
}
StrIntMap w;
countWords(in, w);
for (StrIntMap::iterator p = w.begin( ); p != w.end( ); ++p)
{ std::cout << "\nPress any key to close";
std::cout << setw(30) << left << p->first << " occurred "
<< setw(10) << right << p->second << " times.\n";
}
std::cout << "\nPress any key to close";
getch();
return 0;
}