Counting all printable characters found in a txt file

I'm writing a program that reads and counts all the printable characters (ASCII 32-126)found in a text file.

For example if the text file read: Why so serious?

The output to the screen would display(in order of ascii value however):

Character-----Total
W--------------1
h---------------1
y---------------1
s---------------3
o---------------2
etc...

However, I don't think it's reading any of the characters.

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



int main()
{
	int i, count[94];
	char ch;
	string fname;
	ifstream infile;


	cout<<"Please enter file name: ";
	cin>>fname;
	cout<<endl;

	infile.open(fname);

	for (int i=0; i<94;i++)
	{
		count[i]=0;
	}

	while (infile.get(ch))
	{

		if (ch >= 32 && ch <= 126)
		{
			count[i]++;
		}

		i=ch;
	}

	infile.close();

	cout<<"Character\tTotal"<<endl;
	cout<<"---------------------"<<endl;

	for (i=0;i<94;i++)
	{
		ch=i;
		if (ch >= 32 && ch <= 126 && count[i] > 0)
		{
		cout<<ch<<"\t\t"<<count[i]<<endl;
		}
	}


return 0;
}
Last edited on
When first encounted, i has an indeterminate value on line 26. It is not initialized and using it like you do probably results in you accessing memory that is outside the bounds of the count array. Furthermore you set i to ch inside the loop, knowing that ch may be a value that is outside the bounds of the count array, causing more undefined behavior.

An alternative you may wish to consider:
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 <map>
#include <iostream>

bool is_printable(char ch)
{
    return ch >= 32 && ch <= 126;
}

int main()
{
    std::map<char, unsigned> printable_count;

    unsigned characters_processed = 0;
    char ch;
    while (std::cin.get(ch))
    {
        ++characters_processed;

        if (is_printable(ch))
            ++printable_count[ch];
    }

    unsigned printable_characters = 0;

    for (auto count : printable_count)
    {
        printable_characters += count.second;
        std::cout << count.first << ": " << count.second << '\n';
    }

    std::cout << "Of " << characters_processed << ", ";
    std::cout << printable_characters << " were printable.\n";
}


http://ideone.com/Qm9x6O
Topic archived. No new replies allowed.