I am trying to open a text file, and from this, read each line, and map each word occurrence to the line number it is on. Then, I want to print the map. Here is my code:
#include <map>
#include <set>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main(){
std::map<string, set<int>> myMap;
ifstream myFile;
string myLine ="";
int lineNum = 0;
stringstream myStream;
string myWord ="";
set<int> mySet;
myFile.open("myTextFile.txt");
if(myFile.is_open()){
while (!myFile.eof()){
getline(myFile, myLine);
myStream.str(myLine);
++lineNum;
while (!mySStream.eof())
{
myStream >> myWord;
myMap[myWord].insert(lineNum);
}
myStream.clear();
}
}
myFile.close();
// at this point, I expect everything to have been mapped
// mapping each word occurrence to a line
//I now want to print the map but out does not work, and I need to use an iterator
//I have tried this:
map<string, set<int>>::iterator iter;
for (iter = myMap.begin(); iter != myMap.end(); ++iter)
{
cout << "Key: " << iter->first << endl << "Values:" << endl;
set<int>::iterator setIter;
for ( setIter = iter->second.begin(); setIter != iter->second.end(); ++setIter)
cout << " " << *setIter<< endl;
}
return 0;
}
I have no output. Why not? Secondly, is everything being properly mapped?