eggo
eggo

Reputation: 83

Frequency of Chars

I'm close to finishing my code! I could use some assistance, I've wrote a program that will count the number of letters in a string. My problem comes at the end, when outputting my data. say I enter the string "AAAABBBC"

My expected output should be A-4 B-3 C-1

instead I get C-4 C-3 C-1

any help would be appreciated, my code below

#include <iostream>
using namespace std;




class moose
{
    char inputbuffer[122];
    char countbuffer[122];
    long count;
    short index = 0;

public:
    char charcount();
    char charinput();
    char initialize();

};

int main()
{
    moose obj;
    obj.initialize();
    obj.charinput();
    obj.charcount();
    system("pause");

}


char moose::initialize()
{
    for (int i = 0; i < 122; i++) 
        countbuffer[i] = 0;

    return 0;

}

char moose::charinput()
{
    cout << "Enter your text and I'll read your characters" << endl;
    cin.getline(inputbuffer, 132);
    cin.gcount();
    count = cin.gcount();
    count--;
    return 0;
}

char moose::charcount()
{
    for (int i = 0; i < count; i++)
    {
        if (inputbuffer[i] >= 'a' & inputbuffer[i] <= 'z' || inputbuffer[i] >= 'A' & inputbuffer[i] <= 'Z' || inputbuffer[i] > '0' & inputbuffer[i] <= '9'){
            index = inputbuffer[i];
            countbuffer[index]++;

        }


    }


    for (int i = 0; i <= 122; i++) {
        if (countbuffer[i] > 0)
        {
            cout << char(index) << " - " << int(countbuffer[i]) << endl;
        }
    }


    return 0;
}

Upvotes: 0

Views: 69

Answers (2)

instance
instance

Reputation: 1374

char moose::charcount()
{
    for (int i = 0; i < count; i++)
    {
        if (inputbuffer[i] >= 'a' && inputbuffer[i] <= 'z' || inputbuffer[i] >= 'A' && inputbuffer[i] <= 'Z' || inputbuffer[i] > '0' && inputbuffer[i] <= '9'){
            index = inputbuffer[i];
            countbuffer[index]++;

        }


    }


    for (int i = 0; i <= 122; i++) {
        if (countbuffer[i] > 0)
        {
            cout << char(i) << " - " << int(countbuffer[i]) << endl;
        }
    }


    return 0;
}
  1. Print "i" in place of index.
  2. & - bitwise-AND, use &&

Upvotes: 2

Ufuk Can Bicici
Ufuk Can Bicici

Reputation: 3649

Modify the last loop like in the following:

for (int i = 0; i <= 122; i++) {
    if (countbuffer[i] > 0)
    {
        cout << char(i) << " - " << int(countbuffer[i]) << endl;
    }
}

And convert bitwise ands to logical ands in the first loop (use &&).

By the way, in your case it is better to use a STL container like unordered_map, since you are going to build a histogram of characters actually. If you are going to store the frequency for a few characters in general, it is wasteful to allocate an array indexed by all possible characters, since a lot of the entries will be 0 in the end.

Upvotes: 1

Related Questions