finding a letter in a string

So I'm trying to look for a certain amount of a specific letter in a given string. The letter is also inputted by the user. For some reason I am getting an infinite loop and it isn't counting the letter in the string, can someone point out what I am doing wrong? Obviously it probably deals with my countLetters function and more specifically with my loop, but how would I change it. Here is my code below.

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

/*************************************************************
 * a function that prompts the user for ten grades
 **************************************************************/
void countLetters(char text[], char letter)
{
   int numChar = 0;
   for ( int i = 0; i < text[256]; i++)
   {
      if (text[i] == letter)
      {
         numChar++;
      }
   }
}

int main()
{
   char text[256];
   char letter;
   int numChar;

   cout << "Enter a letter: ";
   cin >> letter;

   cout << "Enter text: ";
   cin >> text;

   cin.ignore();
   cin.getline(text, 256);

   countLetters(text, letter);
   cout << "Number of '" << letter <<"'s: " << numChar;
   return 0;
}
for ( int i = 0; i < text[256]; i++)

What is the value of text[256] ?

Edit:
The countLetters function is ineffective, do you know why ? Hint: Local variable.
Last edited on
for ( int i = 0; i < text[256]; i++)

You only want to loop through as many characters that they entered, which might be less than the size of the initial array. text[256] itself won't be a valid element.

The function can be used to return the letter count back to main (return type int instead of void).

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
#include <iostream>
#include <cstring> // to use strlen
using namespace std;

int countLetters(char text[], char letter)
{
   int numChar = 0;
   for ( unsigned int i = 0; i < strlen(text); i++) // using strlen to get actual length of characters entered
   {
      if (text[i] == letter)
      {
         numChar++;
      }
   }
   return numChar;//return the count to main
}

int main()
{
   char text[256];
   char letter;

   cout << "Enter a letter: ";
   cin >> letter;
   cin.ignore();

   cout << "Enter text: ";
   cin.getline(text, 256);

   cout << "Number of '" << letter <<"'s: " << countLetters(text, letter); // output returned count from function
   return 0;
}
Thanks so much, looks like I was pretty close. I was trying to do it without the cstring library, but I bet this is a ton easier to do than do it another way.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>
#include <algorithm>    // for count()
using namespace std;

int main()
{
   string text;
   char letter;

   cout << "Enter a letter: ";
   cin >> letter;   cin.ignore( 1000, '\n');

   cout << "Enter text: ";
   getline( cin, text );

   cout << "Number: " << count( text.begin(), text.end(), letter );
}


Enter a letter: e
Enter text: No man is an Island, entire of it self; every man is a piece of the Continent, a part of the main.
Number: 10
To those interested, this is how I implemented it, without the cstring library.
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
int countLetters(char text[], char letter)
{
   int numChar = 0;
   for ( int i = 0; text[i]; i++)
   {
      if (text[i] == letter)
      {
         numChar++;
      }
   }
   return numChar;
}

/**************************************************************
 * main will call the functions above and display the result
 ***************************************************************/
int main()
{
   char text[256];
   char letter;

   cout << "Enter a letter: ";
   cin >> letter;
   cin.ignore();

   cout << "Enter text: ";
   cin.getline(text, 256);

   cout << "Number of '" << letter << "'s: "
        << countLetters(text, letter) << endl;

   return 0;
}
Last edited on
for ( int i = 0; i < text[i]; i++) (now changed to for ( int i = 0; text[i]; i++) in code above)

Comparing to a value within the string isn't going to work in all cases. Here it stopped counting halfway through the words.

Enter a letter: a
Enter text: alpha bravo charlie delta echo foxtrot golf hotel india juliet kilo lima mike november oscar papa

i: 0 text[i] is a
i: 1 text[i] is l
i: 2 text[i] is p
i: 3 text[i] is h
i: 4 text[i] is a
i: 5 text[i] is
i: 6 text[i] is b
i: 7 text[i] is r
i: 8 text[i] is a
i: 9 text[i] is v
i: 10 text[i] is o
i: 11 text[i] is
i: 12 text[i] is c
i: 13 text[i] is h
i: 14 text[i] is a
i: 15 text[i] is r
i: 16 text[i] is l
i: 17 text[i] is i
i: 18 text[i] is e
i: 19 text[i] is
i: 20 text[i] is d
i: 21 text[i] is e
i: 22 text[i] is l
i: 23 text[i] is t
i: 24 text[i] is a
i: 25 text[i] is
i: 26 text[i] is e
i: 27 text[i] is c
i: 28 text[i] is h
i: 29 text[i] is o
i: 30 text[i] is
i: 31 text[i] is f
i: 32 text[i] is o
i: 33 text[i] is x
i: 34 text[i] is t
i: 35 text[i] is r
i: 36 text[i] is o
i: 37 text[i] is t
Number of 'a's: 5
Last edited on
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
#include <iostream>
#include <cctype>
using namespace std;

int myCount( char *text, char letter )
{
   int num = 0;
   letter = tolower( letter );
   while( *text ) if ( tolower( *text++ ) == letter ) num++;
   return num;
}

int main()
{
   const int SIZE = 256;
   char text[SIZE];
   char letter;

   cout << "Enter a letter: ";
   cin >> letter;   cin.ignore( 1000, '\n');

   cout << "Enter text: ";
   cin.getline( text, SIZE, '\n' );

   cout << "Number: " << myCount( text, letter );
}


Enter a letter: a
Enter text: alpha bravo charlie delta echo foxtrot golf hotel india juliet kilo lima mike november oscar papa
Number: 10
taking into a/c upper and lower case considerations:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# include <iostream>
# include <string>
# include <cctype>
# include <unordered_map>

int main()
{
    std::string text =
        "No man is an Island, entire of it self; every man is a piece of the Continent, a part of the main.";
    std::unordered_map<char, size_t> letterCount{};
    for (auto& elem : text)
    {
        if(isalpha(elem))
        {
            elem = tolower(elem);
            ++letterCount[elem];
        }
    }
    for (const auto& elem : letterCount)std::cout << elem.first << " " << elem.second << "\n";
}
Last edited on
I was trying to do it without the cstring library, but I bet this is a ton easier to do than do it another way.

C++ standard library is there to simplify your life. Anyway also C programmers face problems like that:
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
#include <cstdio>
#include <cstring>
#include <iostream>
#include <limits>


int countLetters(char* text, char letter);
void waitForEnter();


int main()
{
    std::cout << "Enter a letter: ";
    char letter;
    std::cin >> letter;
    std::cin.ignore(1);

    std::cout << "Enter text: ";
    char text[256];
    std::scanf("%256[^\n]s", text);

    int recurrences = countLetters(text, letter);
    std::cout << "Number of '" << letter << "'s: " << recurrences << '\n';
    waitForEnter();
    return 0;
}


/*************************************************************
* a function that prompts the user for ten grades
**************************************************************/
int countLetters(char* text, char letter)
{
    int recurrences = 0;
    while(*text != '\0') {
        if(*text == letter) { recurrences++; }
        text++;
    }
    return recurrences;
}


void waitForEnter()
{
    std::cout << "\nPress ENTER to continue...\n";
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

Ops! Many apologizes, I didn't notice the thread was marked as solved!
1
2
3
    std::cout << "Enter text: ";
    char text[256];
    std::scanf("%256[^\n]s", text);

Do you realize that you have a possible buffer overflow error in the above code?

Also mixing C++ streams and C-stdio functions is not recommended.
jlb wrote:
Do you realize that you have a possible buffer overflow error in the above code?

Hi, jlb. Thank you for you advice.
Should I have written
std::scanf("%255[^\n]s", text);
instead?
Yes, remember you need to reserve room for the end of string character with scanf(), or perhaps just use fgets() instead.

And don't forget mixing C-stdio function with C++ streams can be hazardous at times.

Topic archived. No new replies allowed.