Write a C++ program that queries the user for an input string and a 3-character
ID: 670749 • Letter: W
Question
Write a C++ program that queries the user for an input string and a 3-character substring. Then perform the following: 1. Check length of substring; print error and return if not equal to a length of 3 2. Find location of the substring in the input string. Print error and return if the substring is not found 3. Print location of the substring. Position 0 is the first character of the string. 4. Remove the substring from the input string. 5. Determine if the new string is a “magic” string, in which case print “Magic string!”. A “magic” string is one for which the length is a multiple of 5, and the 5th character is a vowel. You program must have the following: • Three lines of comments at the top with your name, program name, and the date created. • Use variables of type string • Use getline() function to obtain a phrase that may contain spaces • Using constant string::npos to determine when the substring does not appear • Use string function replace() to remove the substring • Use string function find_first_of() to find if vowel at the magic position • Use compound logical statement when determining whether a magic string
Sample Output (four possibilities shown)
Enter a phrase: All in a one shot frame Enter a 3-character sub-string: sho Substring occurs at position 13 Phrase without substring is: All in a one t frame Magic string!
Enter a phrase: All in a one week period Enter a 3-character sub-string: week Incorrect length of substring
Enter a phrase: This is how we get things done Enter a 3-character sub-string: thi Substring occurs at position 19 Phrase without substring is: This is how we get ngs done Not a magic string.
Enter a phrase: All in a one shot frame Enter a 3-character sub-string: abc Substring does not appear in the phrase
Explanation / Answer
#include <iostream>
#include<string>
using namespace std;
int main()
{
string String,sub;
int flag=0;
cout << "Enter the String: " << endl;
getline (std::cin,String);
cout<<"enter the substring of size 3 characters: ";
getline(std::cin,sub);
if(sub.length()==3){
//string str3 = String.substr (sub);
//cout<<"string: "<<str3;
if(String.find(sub) != string::npos){
cout<<"entered string has sub-string"<<endl;
size_t pos = String.find(sub);
cout<<pos<<endl;
String.erase (pos,3);
cout<<"After deleting the string is: "<<String<<endl;
std::size_t found = String.find_first_of("aeiou");
if((String.length()%5)==0){
while (found!=std::string::npos)
{
found=String.find_first_of("aeiou",found+1);
if(found==4){
cout<<"Magic Word"<<endl;
flag=1;
break;
}
}
if(flag==0){
cout<<"Not a magic word!!"<<endl;
}
}
else{
cout<<"not a magic word"<<endl;
}
}
else{
cout<<"substring not found!!!!"<<endl;
}
}else{
cout<<"Error wrong sub string: ";
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.