Character Count Program

I have this character count program that takes the Gettysburg Address from an input file and is supposed to count how many of each letter there are. Problem is when I run it, it gives me an infinite loop of the characters and all there counts say some big negative number like -85620 or something. Now I know this means I have an infinite loop or something else amateur, but I am new to programming and do not quite understand my problem. Here is my code:

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

void characterCount(char character, int list[]);
void countFunction(int list[]);
void totalCount(int list[]);

int main()
{
	int counters[26];
	int count = 0;
	char inFileName[128];
	cout << "Enter the input file: ";
	cin >> inFileName;
	ifstream inFile;
	inFile.open(inFileName);
	if(! inFile.is_open()){
		cout << "ERROR: Failed to open " << inFileName << endl;
		cout << "Now exiting...\n";
		exit(-1);
	}

    while (!inFile.eof())
    {
        totalCount(counters);
    }
	
	return 0;
}

void countFunction(int list[]){
 
     for(int i = 0; i < 26; i++)
             list[i]=0;
}

void characterCount(char character, int list[]){
     int index;
     character = tolower(character);
     index = static_cast<int>(character)-static_cast<int>('a');
     if (0 <= index & index < 26)
           list[index]++;
}

void totalCount(int list[]){
     int index;
     for(index = 0; index < 26; index++)
		cout << static_cast<char> (index + static_cast<int>('a')) << ": " << list[index] << endl;
}

It does not look like you are processing the file at all. This is the source of your infinite loop.

What you need to make sure of is that the array counters is initialized to 0 (use your countfunction()) and then step by step process each line of the address. (read in each line and then process it character by character)

try this:

string line;

while (!inFile.eof())
{
getline(inFile, line);

for(int i = 0; i < line.length(); i++)
{
if(tolower(line[i]) <= 122 && tolower(line[i]) >= 97)
{

counters[tolower(line[i]) - 97]++;
}
}
}
When I do this it simply does nothing and just says press any key to continue...
Topic archived. No new replies allowed.