I am writing a program that prompts a user to enter a sentence and then has a function that counts the letters in that sentence. For instance it will display how many a's, b's, c's, d's, etc. Also it will count numbers and the total characters including spaces. I have it compiling as of now and the input function and the quit option are working correctly but I am struggling with the counting function. Anyone have any ideas?
An ASCII table has 127 decimal values. This is why your CharCountBuf is 127 elements (see http://www.asciitable.com/).
First convert inbuf[i] to a short, similar to what you do on line 60... but do it to the actual character, not just 'a'. Once you have done that, the if condition on line 58 probably just needs to check that the short you have representing that character is between 0 and the size of your array. If it is, you can increment the "charval" element in the array. Think of it this way - each element in your array is a character, and charval is the character's index in that array.
Once you've done that, you have successfully counted all the characters.
If you need to count the total characters (assuming some characters in your string might have been ignored due to not being an ASCII character), you can add all the elements in your array together to get the total number of ASCII characters.
tscott8706,
Thank you so much for the response. I really appreciate the help. I've read your response and when I get home today I will be working on it and I'll post with what progress I've made!
I'm trying to implement what you're saying but I'm still having difficulty unfortunately. Is there anywhere you could write some of it out so I can visually see what you're saying to do?
It's just dawned on me that what you are saying is counting the number of characters in the user's sentence. I need to count and display how many of EACH character and how many of EACH number are in the sentence. For example how many "a's", how many "b's", how many "c's", and so on.
What tscott8706 described did end up with counting the number of characters in the sentence, but you could easily change the end to output how many of each character was counted.
This is what I mean, and sort of like what tscott8706 described:
1 2 3 4 5 6 7 8 9 10 11 12 13
void CountAndDisplay(char* inbuf, int &count)
{
short CharCountBuf[128] = {0}; //ASCII values 0 to 127 is a total of 128 values
for (int i = 0; i < count; i++)
if ((inbuf[i] < 128)
++CharCountBuf[inbuf[i]];
for (char c = 'a'; c <= 'z'; ++c)
cout << c << " - " << CharCountBuf[(short)c] << endl;
for (char c = 'A'; c <= 'Z'; ++c)
cout << c << " - " << CharCountBuf[(short)c] << endl;
system("pause");
}