once again I ask for help. I haven’t coded anything for sometime!
Now I have a text file filled with random gibberish. I already have a basic idea on how I will count the number of occurrences per word.
What really stumps me is how I will determine what line the word is in. Gut instinct tells me to look for the newline character at the end of each line. However I have to do this while going through the text file the first time right? Since if I do it afterwords it will do no good.
I already am getting the words via the following code:
vector<string> words;
string currentWord;
while(!inputFile.eof())
{
inputFile >> currentWord;
words.push_back(currentWord);
}
This is for a text file with no set structure. Using the above code gives me a nice little(big) vector of words, but it doesn’t give me the line they occur in.
Would I have to get the entire line, then process it into words to make this possible?
Use a
std::map<std::string, int>to count the word occurrences — theintis the number of times it exists.If you need like by line input, use
std::getline(std::istream&, std::string&), like this:You can split a line apart by putting it into an
std::istringstreamfirst and then usingoperator>>. (Alternately, you could cobble up some sort of splitter usingstd::findand other algorithmic primitaves)EDIT: This is the same thing as in @dash-tom-bang’s answer, but modified to be correct with respect to error handing: