Need help changing code.

This code determines the frequency of letters in a text file:


As of right now this code couts all the letters in the alphabet. So for example, if there are 0 z's in the text file, it couts
Z: 0

But I don't want it to display letters that aren't in the file. How can I make it only show the amounts for letters that are actually in the file?
Last edited on
Hi,

freq[ch] holds the count of the character. Maybe if that number equals 0 you can skip it.

Btw. why do you have a C-vector of size 192 and only initialize 128 of them with 0?
Because of the numeric values of A and Z?
Hint: you can do calculations like x - 'A'.

Regards,
Mathes
Last edited on
Hey Thanase lets see the below code, i think your problem is shut out. the correction is quoted in "==========" . if not solved please say the problem.

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
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
   int freq[192];    
   ifstream inFile;   
   char ch; 

   inFile.open("x.txt");

   for (int k = 0; k < 128; k++)
   {
      freq[k] = 0;
   }

   ch = inFile.get();
   while (ch != EOF)
   {
      cout << ch;
      ch = toupper(ch);
      freq[ch]++;
      ch = inFile.get();
   }
  cout << endl << "Letter:        Frequency:" << endl;
  for (char ch = 'A'; ch <= 'Z'; ch++)
  {//==========================================
      	if(freq[ch] != 0)
   //==========================================	
		cout << ch << " :            " << freq[ch] << endl;
  }
  system("pause");
  return 0;
}
Last edited on
Hey that worked, thanks man.
The OPer has a habit of blanking their posts. This is a quote of the first post.
Thanase wrote:
This code determines the frequency of letters in a 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
#include <fstream>
#include <iostream>
using namespace std;

int main()
{
   int freq[192];    
   ifstream inFile;   
   char ch; 

   inFile.open("x");

   for (int k = 0; k < 128; k++)
   {
      freq[k] = 0;
   }

   ch = inFile.get();
   while (ch != EOF)
   {
      cout << ch;
      ch = toupper(ch);
      freq[ch]++;
      ch = inFile.get();
   }
  cout << endl << "Letter:        Frequency:" << endl;
  for (char ch = 'A'; ch <= 'Z'; ch++)
  {
      cout << ch << " :            " << freq[ch] << endl;
  }
  system("pause");
  return 0;
}


As of right now this code couts all the letters in the alphabet. So for example, if there are 0 z's in the text file, it couts
Z: 0

But I don't want it to display letters that aren't in the file. How can I make it only show the amounts for letters that are actually in the file?
Topic archived. No new replies allowed.