Here's a possible solution for the problem:
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::vector<std::string> fruits = // what fruits are in the program (pineapple is not part of this vector)
{
"apple",
"banana",
"cherry",
"coconut",
"grape",
"lime",
"orange"
};
std::cout << "===========================" << std::endl << std::endl;
std::cout << "Welcome to our Fruit Finder" << std::endl << std::endl;
std::cout << "===========================" << std::endl << std::endl;
std::cout << "Your fruit list contains: ";
bool first = true;
for (std::string fruit : fruits)
{
if (first)
first = false;
else
std::cout << ", ";
std::cout << fruit;
}
std::cout << std::endl << std::endl << "Please enter a sentence containing a fruit from the list above: ";
std::string sentence;
std::getline(std::cin, sentence);
std::cout << "Would you like to replace a fruit from your sentence? (Yes or No?): ";
std::string input;
std::cin >> input;
if (input == "Yes")
{
std::string fruitToReplace;
std::string replacementFruit = "pineapple";
std::vector<std::string>::const_iterator it;
do
{
std::cout << "Which fruit will you replace? : ";
std::cin >> fruitToReplace;
it = std::find(fruits.cbegin(), fruits.cend(), fruitToReplace);
}
while (it == fruits.cend());
std::cout << "Replacing " << *it << " by " << replacementFruit << "..." << std::endl;
for (size_t start = 0; (start = sentence.find(fruitToReplace, start)) != std::string::npos; start += replacementFruit.length())
{
if (start != std::string::npos)
sentence.replace(start, fruitToReplace.length(), replacementFruit);
}
std::cout << "After replacement: " << sentence << std::endl;
}
return 0;
}