Number of characters

Trying to write a program to count number of characters but it returning zeros most of the time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int main()
{
   char letter = '\0';
   cout << "Enter a letter: ";
   cin >> letter;
   string text = "";
   cout << "Enter text: ";
   cin >> text;
   int number = 0;
   {
      for (int i = 0; i < text.length() ; i++) {
         if (text[i] == letter) {
         number++;
         }
      }
   }
   cout << "Number of '" << letter << "'s: " << number <<  endl;
   return 0;
}


I left everything on Main just to make it simpler. What do you think I'm doing wrong?
Last edited on
It's because you set:
char letter = '\0';

If you remove the initialization, it's going to work.

Also, I coded this quickly, this program can deal with comparison of lower case letters to upper case.

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
#include <iostream>
#include <string>
using namespace std;

int numOfChar(string text, char letter)
{
	int numOfChar = 0;
	for (int i = 0; i < text.length(); i++)
	{
		if (text[i] == letter)
		{
			numOfChar++;
		}
	}
	return numOfChar;
}

int main() 
{
	string text;
	char letter;
	int Result = 0;       // number of same letter in a word
	cout << "ENTER LETTER: ";
	cin >> letter;
	cout << "ENTER TEXT: ";
	cin >> text;
	//covert letter to capital for better comparison
	letter = toupper(letter);
	//convert all of the string to capital for better comparison
	for (unsigned int i = 0; i < text.size(); i++)
	{
		text[i] == toupper(i);
	}
	Result = numOfChar(text, letter);
	cout << "THE NUMBER OF SAME LETTERS IN A WORD IS " << Result << endl;
	system("PAUSE");
	return 0;
}
Last edited on
Topic archived. No new replies allowed.