Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results.
Write a program to create a Mad Libs like story. The program should read a multiline story from the input. The story will be terminated with a blank line. Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements. Stop when there are none left and print the final story.
The input should be in the form:
<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home.
It should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value.)
#include <iostream> #include <string> using namespace std; int main() { string story, input; //Loop while(true) { //Get a line from the user getline(cin, input); //If it's blank, break this loop if(input == "\r") break; //Add the line to the story story += input; } //While there is a '<' in the story int begin; while((begin = story.find("<")) != string::npos) { //Get the category from between '<' and '>' int end = story.find(">"); string cat = story.substr(begin + 1, end - begin - 1); //Ask the user for a replacement cout << "Give me a " << cat << ": "; cin >> input; //While there's a matching category //in the story while((begin = story.find("<" + cat + ">")) != string::npos) { //Replace it with the user's replacement story.replace(begin, cat.length()+2, input); } } //Output the final story cout << endl << story; return 0; }
Content is available under GNU Free Documentation License 1.2.