Sorry im new to c++ can some one tell me how to get this program to count the number of occurences of a letter in a string and out put that to the screen after my word count
thanks
# include <iostream>
# include <string>
using namespace std;
int WordCount(string sentence);
int main()
{
string Mystring;
cout << "type in the string you would like to use: ";
cout << endl;
getline(cin, Mystring); // input sentence
cout << " Your string is: ";
cout << Mystring;
cout << endl;
cout << " The string has ";
cout << WordCount(Mystring);
cout << " words ";
cout << endl;
system("pause");
return 0;
}
//counts the words
int WordCount(string Sentence)
{
// gets length of sentence and assigns it to int length
int length = Sentence.length();
int words = 1;
for(int size = 0; length > size; size++)
{
if(Sentence[size] == ' ' && Sentence[size-1] !=' ')
words++;
}
if(Sentence[0] == ' ')
{
words--;
}
It's probably better to use a new LetterCount function that takes the string and the letter you want to count. In the function, traverse the string again and increment some counter each time the letter from the string matches the letter passed in. You then return that value at the end of the function. You already know how to display the value.
I undestand how to output the count to the screen but I cant figure out a function that will count the letters
also im having trouble with getting the program to quit was the user has finished i tryed a do while loop-- while(WordCount != 0) but when i type 0 it just give me another loop
any help would be I would be greatfull
int LetterCount(std::string s, char letter)
{
int count = 0;
int length = s.length();
for (int size = 0; size < length; ++size)
{
// check if the i'th character in s matches letter. If so, increment count.
}
return count;
}
This is very similar to your WordCount function. You need to fill in the bit that's different yourself.
There is an excellent algorithm within the STL that provides this functionality. Unless you have a requirement to write the algorithm yourself use std::count. It works with many kinds of containers including strings. Use the std::string::begin and std::string::end functions to pass the iterators to the function and follow the example. If you were told to write a program that performs this it doesn't necessarily mean that you have to write the algorithm when you can use std::count within the program. http://cplusplus.com/reference/algorithm/count/