Problem with the overlap of input

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:

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
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
using namespace std;

const int numofletters = 26; //# of letters in the alphabet
const int 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!
Last edited on
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] = {};)
Topic archived. No new replies allowed.