Ifstream character problem

This is what I'm trying to do:
"Write a program which prints a table listing the number of occurrences of the lower-case characters 'a' to 'z' in the file "Sheet5Ex5.cpp". (Save your program in a file of this name so that you can test it on itself.) Write your program as though your computer is short of memory - you should declare only one variable of type "ifstream", one variable of type "char", and two variables of type "int". The program should produce output such as the following:
CHARACTER OCCURRENCES

a 38
b 5
c 35
d 7
e 58
f 8
g 8
h 21
i 32
j 0
k 0
l 19
m 16
n 34
o 22
p 8
q 0
r 48
s 17
t 61
u 15
v 0
w 4
x 4
y 0
z 1
"

I made "Sheet5Ex5.cpp" file,and added bunch of radnom text inside it, and I made the code. My output is that letter 'a' is counted 169 times,and all other letters are counted 0 times. This is the 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
  #include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{   ifstream input;
    int counter;
    char Char='a';
    char b;
    input.open("Sheet5Ex5.cpp");
    cout<<"\t\tCHARACTER\t\t\tOCCURENCES"<<endl;
    if(input.is_open())
    {
            counter=0;
            for(int i=0;i<26;i++)
            {counter=0;
                for(; input.get(b) ;)
                {
                    if( Char==b){counter++;}
                }


                cout<<"\t\t"<<Char<<"\t\t\t\t"<<counter<<endl;
                Char++;
            }
    }


    else
    {
        cout<<"Couldn't read the file."<<endl;
    }


    return 0;
}
Last edited on
Maybe this might help:
1
2
3
4
for(char ch = 'a'; ch <= 'z'; ch++)
{
    std::cout << ch << ", ";
}
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, 


Your Char variable is not looping across the whole alphabet.

Edit: nvm I just saw the Char++ on line 24
Last edited on
Topic archived. No new replies allowed.