Reading text file and displaying each word with it's frequency on output

I have made this program which will give the word with it's frequency on output but I want to make it like it would automatically end program when all words are read in text file Right now it is iterating 100 times no what how many words are in text file

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
  #include<fstream>
#include<iostream>
#include<conio.h>
#include<sstream>
using namespace std;
int main()
{
	int y=0,x=0,z;
	string arr[100][2];
    string word,ch;
	ifstream obj;
	
	obj.open("New folder/Doc1.txt");
	if(!obj)
	{
		cout<<"file not found";
	}
	else
	{
		while(obj>>word)
		{
			for(int i=0;i<100;i++)
			{
				if(word==arr[i][0])
				{
					y=1;
					stringstream s1,s2;
					s1<<arr[i][1];
					s1>>z;
					int w=z+1;
					s2<<w;
					s2>>ch;
					arr[i][1]=ch;
					break;
				}
			}
			if(y==0)
			{
			arr[x][0]=word;
			arr[x][1]="1";
			x++;
			}
			else
			y=0;
		}
	}
	for(int i=0;i<100;i++)
	{
		for(int j=0;j<2;j++)
		{
			cout<<arr[i][j];
			cout<<"\t";
		}
		cout<<endl;
	}
	
}
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
#include <fstream>
#include <iostream>
#include <sstream>
#include <map>
#include <cctype>
using namespace std;

string lowerCase( string s )
{
   for ( char &c : s ) c = tolower( c );
   return s;
}


int main()
{
//  ifstream in( "Doc1.txt" );
    istringstream in( "Three blind mice\n"
                      "Three blind mice\n"
                      "See how they run\n"
                      "See how they run\n"
                      "They all ran after the farmer's wife\n" );
                      
    map<string,int> freq;
    for ( string word; in >> word; ) freq[lowerCase(word)]++;
    
    for ( auto p : freq ) cout << p.first << ": " << p.second <<'\n';
}


after: 1
all: 1
blind: 2
farmer's: 1
how: 2
mice: 2
ran: 1
run: 2
see: 2
the: 1
they: 3
three: 2
wife: 1
Brother requirement of my program is to use 2d array
Brother requirement of my program is to use 2d array


Using a string to do the counting ... is utterly bonkers.


A map is a perfectly good "2d array" in this particular problem. Its dimensions are effectively size x 2, whilst you are (attempting to) use an array of dimensions 100 x 2.
Last edited on
Topic archived. No new replies allowed.