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
#include <iostream>
usingnamespace 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();
}
elseif (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
#include <iostream>
#include <string>
#include <cstring>
usingnamespace std;
void function();
string sentence;
char test,*pointer,letter;
int counter=0;
int main(){
bool a = true;
function();
while (a){
counter =0;
cout<<" yes or no "<<endl;
cin>>test;
if (test =='y'){
function();
}
elseif(test == 'n'){
a = false;
}
else {
cout<<"Enter y or n: "<<endl;
}
}
return 0;
}
void function(){
cin.ignore(); //when you first start the program you have to press enter cause of this line of code
cout<<"Enter a sentence: "<<endl;
getline(cin,sentence);
cout<<"Enter a letter: "<<endl;
cin>>letter;
for (int i=0; i <= sentence.size(); i++){
if (sentence[i] == letter)
counter++;
}
cout<<"The sentence is : "<<sentence<<" and the letter "<<letter<<" is found "<<counter<<" times"<<endl;
}