Hello all! Im finished this piece of code and it seems to work without the while loop but I'm trying to loop this piece of code over and over without stopping it until the user enters 'Q' or some type of command to end the code.
Here is my code:
#include <iostream>
usingnamespace std;
constint numofletters = 26; //# of letters in the alphabet
constint size = 100; // Maximum int size of 100
void count(char [], int []); // delcaration of void function prototype
int main()
{
while(true)
{
int counts[numofletters] = {}; //initialize counts
char userstring[size];
cout << "Enter a string: "; // Prompt to enter the string
cin.getline(userstring, 256); // get 256 characters of the string
cin.clear();
count(userstring, counts); // Reference to void function "void count"
for (int i = 0; i < numofletters; i++)
{
if(counts[i]>0)
{
cout << char(i + 'a') << ": " << counts[i] << " times\n"; // adding count of letters
}
}
}
}
void count(char s[], int counts[])
{
for (int i = 0; i < numofletters; i++) //Going through loop of letters in alphabet
{
counts[i] = 0; // Going through alphabet
}
for (int i = 0; i < size; i++) // loop of size of string
{
{
s[i] = tolower(s[i]); // If A is used, convert to a.
// Both is used towards 'a' counter
counts[s[i] - 'a'] ++; // counting number
//of letters in the string and
//adding the amount to the letter
}
}
}
Every time I enter multiple inputs, the last letter seems to overlap and mess up the character count and i don't know what I'm doing wrong!
The problem is in count. You are counting every character in s even though you should only be counting characters up to the first NUL character encountered.
1 2 3 4 5
void count(char s[], int counts[])
{
while (*s)
++counts[tolower(*s++) - 'a'];
}
Note that you are missing a #include <cctype> for tolower. Zeroing the counts array is not necessary in count as it is done each iteration of the while loop before count is called (int counts[numofletters] = {};)