Prompt user to input a string and a character then display the 3 positions of occurrence of the input character
Hint: You could find yourself needing the assistance of more than a single string function.
Example 1:
• Sample Input:
“Hippopotamus”
“p”
• Sample Output:
“The letter p has occurred in positions 2, 3 and 5”
Example 2:
• Sample Input:
“Glasses”
“s”
• Sample Output:
“The letter s has occurred in positions 3, 4 and 6”
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
string word;
char character;
cout<<"Please write any word then enter the char that you wish to find it's position"<<endl;
cin>> word>>character;
//i don't know what to do next
//note that i'm still learning
//and only know of this two things
//iostream and string
return 0;
}
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
string word;
char character;
cout<<"Please write any word then enter the character that you wish to find it's positions in the word"<<endl;
cin>> word>>character;
//i don't know what to do next
//note that i'm still learning
//and only know of this two things
//iostream and string
int q = word.find(character);
int w = word.find(character);
int e = word.find(character);
int r = word.find(character);
int t = word.find(character);
cout<<q<<w<<e<<r<<t;
return 0;
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
string word;
char character;
cout<<"please enter a word then enter the character that you wish to findit'sposition"<<endl;
cin>> word>>character;
int q = word.find(character);
string tempword = word.substr(q+1);
int w = tempword.find(character);
tempword = word.substr(w+1);
int e = tempword.find(character);
tempword = word.substr(e+1);
cout<<"The character positions are "<<q<<" "<<w<<" "<<e<<endl;
return 0;
}
Not a problem. I didn't test it, just wrote it from memory. I hope it works for you. You were definitely on the right track. Just needed the correct method of determining the individual character.
• Sample Output:
“The letter s has occurred in positions 3, 4 and 6”
The output formatting is an another thing. You have four cases:
A. 0: "does not occur"
B. 1: "occurs in position X"
C. 2: "occurs in positions X and Y"
D. >2: "occurs in positions ZZ and Y", where ZZ is a comma separated list with at least two entries
You don't know which format you have to use before you have checked the whole word.