Nov 12, 2017 at 7:36pm Nov 12, 2017 at 7:36pm UTC
hi im trying to create a program that counts words from a .txt file and any time it encounters a new word it starts counting how many of that word are in the file as well but i can't seem to find a way to do this.
Last edited on Nov 12, 2017 at 10:27pm Nov 12, 2017 at 10:27pm UTC
Nov 12, 2017 at 7:55pm Nov 12, 2017 at 7:55pm UTC
A map comes to mind.
Read word. Check if word is in map. If not, create new entry in map (key = new word) with value zero. If it is in the map, increment the entry with key == word by one.
Nov 12, 2017 at 7:56pm Nov 12, 2017 at 7:56pm UTC
do you mind showing me an example i haven't worked with maps before each line of the file has one word on it
Last edited on Nov 12, 2017 at 8:00pm Nov 12, 2017 at 8:00pm UTC
Nov 12, 2017 at 8:20pm Nov 12, 2017 at 8:20pm UTC
thank you i appreciate your help i think this will work i just need to read each line of the .txt file and put the word on that line in the map. i think.
Nov 12, 2017 at 9:02pm Nov 12, 2017 at 9:02pm UTC
@Repeater
theMap[word] = 0;
shouldn't the count then be 1 if it is added?
Nov 12, 2017 at 11:36pm Nov 12, 2017 at 11:36pm UTC
i do want to read the whole line there is one word per line in the file but im trying to make sure that my words are getting inserted into the map
Nov 12, 2017 at 11:48pm Nov 12, 2017 at 11:48pm UTC
i believe i have a working version
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
#include <iostream>
#include <fstream>
#include <string>
#include <map>
using namespace std;
int main () {
string line;
ofstream outputFile("test.txt" );
ifstream myfile ("tim.txt" );
map<string,int > words;
string it;
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
if (words.find(line) != words.end())
{
words[line]++;
cout<<line<<endl;
cout<<"word exists" <<endl;
}
else
{
words[line] = 1;
cout<<line<<endl;
cout<<"word dosent exist" <<endl;
}
}
myfile.close();
}
return 0;
}
Last edited on Nov 13, 2017 at 12:03am Nov 13, 2017 at 12:03am UTC
Nov 13, 2017 at 12:07am Nov 13, 2017 at 12:07am UTC
i now need to print the all of the keys and values from the map to the console if i could get some help with that.