string help

Sometimes it reads all the letters in the string, most of the time it only reads them a few times, any help?
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
#include <iostream>
#include <string>
using namespace std;

const int size = 100;
const int numberOfLetters = 26;
void count(char[], int[]);

int main()
{
	if (system("CLS")) system("clear"); //clears garbage from screen

	int counts[numberOfLetters];
	char s[size];


	cout << "Enter a string: ";
	cin.getline(s, '\n');



	count(s, counts);

	for (int i = 0; i < numberOfLetters; i++)
	{
		if (counts[i]>0)
		{
			cout << char(i + 'a') << ": " << counts[i] << " times." << endl;
		}
	}

}

void count(char s[], int counts[])
{
	for (int i = 0; i < numberOfLetters; i++)
	{
		counts[i] = 0;
	}

	for (int i = 0; i < size; i++)
	{
		{
			s[i] = tolower(s[i]);
			counts[s[i] - 'a'] ++;
		}
	}
}
line 41 - i goes all the way up to size (100) even if the text entered is shorter. The count should only go the length of the text actually entered.

Since you've included <string>, you could use a string - unless you're required to use character arrays?
I see the problem with line 41, any idea what I can add to make it so it only takes the length of the entered string?
If you make the input a string instead of a character array, you can use the string length() function to get the actual length.

http://www.cplusplus.com/reference/string/string/length/
Topic archived. No new replies allowed.