Hi
I am attempting to write a code that will input the name of a file and output the number of times each letter appears in the file, and it is case-insensitive.For example :
a|A : 5
b|B : 3
c|C : 0
d|D : 7
e|E : 0
so on..
So far i have been able to write this code.the problem with my code is that it outputs the number of characters after every string and that the characters that are supposed to be zero,my code outputs some large number instead of it.I would really appreciate your help! :)

#include <iostream>
#include <cdtg>
using namespace std;

const int N = 26;

void countLetters(string str);

int main()
{
string file_name = "";
cout << "Please input name of file: ";
getline(cin,file_name);
InputFile file(file_name);

while (!file.eof()) {
string str = "";
file.getline(str);
countLetters(str);
}
file.close();
return 0;
}


void countLetters(string str)
{
char alphabet[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 
	'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 
	'v', 'w', 'x', 'y', 'z'};
int count[N];
int i=0;
while ( i<str.length())
  {
    str[i] = tolower(str[i]);

    for (int j = 0; j < N; j++)
    {

      if (str[i] == alphabet[j])
      {
       count[j]++;
       break;
      }
    }
	i++;
  }
for (int b = 0; b < N; b++)
    {
     cout << alphabet[b]<<"|";
	 alphabet[b] = toupper(alphabet[b]);
	 cout<<alphabet[b] <<": "<< count[b] << endl;
    }

}

Recommended Answers

All 5 Replies

don't use eof() use file.is_good();

Also, the reason you are getting random numbers is because you don't initialise your array.

int count[N];

becomes

int count[N] = {0};

The reason it prints after everyline is because you call your function for each line, and it is your function that prints


Chris

Thank a bunch for your help! I initialized my array and its giving zeros now.Actually im bound to use eof() in my code.Whenever i call the funtion countLetters in 'int main()' it initializing count[N] = {0} everytime and therefore my count of characters of previous lines are lost.Can you help me round this problem? And also how to only output the letters only after the end of file?I would really appreciate it!

Pass the count array to your function, then increment its values and print out after the whole file has been read.

void countLetters(string str, int* count);

...

int totals[N] = {0};
    while (getline(file, str) != NULL) {
        countLetters(str, totals);
    }

Thanks a million for you help! :)

commented: thak you +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.