Hello, I'm new to C++ and having some small difficulties with creating and calling functions. The program has the user enter a sentence, then a letter. The program will return how many times the letter is used in the sentence.
Everything I have written technically works, but I think my problem has to do with my loop coding. My output is currently this:
Enter a sentence: (user input)
Enter a letter: (user input)
The letter __ is used __ times.
Would you like to test another sentence? (y/n): (user input)
And this works perfectly if the user chooses no, but if they choose yes is where it starts confusing me. Here is my code
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 49 50 51 52 53 54 55 56 57 58
|
#include <iostream>
using namespace std;
void sentence();
int main()
{
char answer;
bool test = true;
sentence();
while (test == true)
{
cout << "Would you like to test another sentence? (y/n): ";
cin >> answer;
if (answer == 'y')
{
sentence();
}
else if (answer == 'n')
{
cout << "Ending program.\n";
test = false;
}
else
{
cout << "Please enter either 'y' or 'n': ";
}
}
return 0;
}
void sentence()
{
char sent[500];
char letter;
char answer;
int count = 0;
cout << "Enter a sentence: ";
gets(sent);
cout << "Enter a letter: ";
cin >> letter;
for (int i = 0; i < strlen(sent); i++)
{
if (sent[i] == letter)
{
count++;
}
}
cout << "The letter " << letter << " is used " << count << " times.\n";
}
|
If the user chooses yes, I get this as the output:
Enter a sentence: Enter a letter:
So I'm not really sure how to structure my loop correctly or if something is wrong with how I'm calling the function but this is confusing me. Any suggestions would be great. Thanks