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.
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).
#include <iostream>
#include <cstring> // to use strlen
usingnamespace std;
int countLetters(char text[], char letter)
{
int numChar = 0;
for ( unsignedint 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.
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
# 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 (constauto& elem : letterCount)std::cout << elem.first << " " << elem.second << "\n";
}