Question

Question(C++). Please write a C++ code, it will generate a conversation between Hans and Beatrice by...

Question(C++). Please write a C++ code, it will generate a conversation between Hans and Beatrice by randomly selecting phrases and sentences from files, then altering them before output

The code will start the conversation between Hans and Beatrice by having Hans say "hello" (it's him who makes the call). This is to be followed alternately by Beatrice and then Hans saying something. Each thing they say will be chosen at random from their respective files, HansSayings.dat and BeatriceSayings.dat. But before each saying is displayed to the screen, they are to be altered by the code in the following manner. Some words need to be "sanitized" for the general public (you never know, this could become a TV show!). Each "bad" word is to be replaced with a "good" word. Here's how they are to be replaced:

idiot - > mean person
dammit - > darn it
shOt - > poop
crOp - > poopie
daOn - > hoot

The entire “sanitized-version” of the conversation should be written to an output file “Conversation.dat”

Details:
1. Each of the sayings files is formatted with the first line containing an integer indicating how many sayings there are in the file, and the remaining lines each have a saying of at most 256 chars.

2. If the "bad" word begins with an uppercase letter in the saying, then the "good" word it is replaced with must also begin with an uppercase letter in the saying.

3. The telephone conversation ends when 20 rounds (NOT individual utterances) of Beatrice and Hans saying something have been completed.

4. At the end of the conversation, Beatrice and Hans should say 'goodbye' to each other, (i.e., it was over because 20 rounds of the telephone conversation finished).

Here is the input file about the sayings of the two people:

Hans.dat

25
Mother, why are you such an idiot?
You know, I remember when you tried to drown me in the bathtub when I was 22!
Do you need me to donate blood for you again?
idiot, idiot, idiot!
Dammit, mother! Why do you keep bringing that up?
Mother, Butterscotch has been dead for years.
Oh, that's just a bunch of crOp!
You're full of shOt!
Do you need your teeth filed? Your tongue has certainly gotten sharp!
You know, I might call you more often if you'd say nice things to me!
Nag, nag, nag!
Oh, geez. Give it a rest!
Dammit, don't you have anything nice to say?
Have you been drinking?
Why can't you be proud of my acting career?
I don't mean to be indelicate, but when was the last time you were de-wormed?
Are you taking your medications?
You know, eating hay might help keep your regular.
Did the glue factory people stop calling you?
Saying things like that hurts my feelings...

Beatrice.dat

30
Oh, big stud! Always running around to gallivant with your fillies!
Remember, don't sit too close to the TV, it will make you cruel!
You know, I was beautiful before I had you.
I'm sorry, did you need a compliment?
Oh, this letter I have? It's from the government saying I'm proud of you!
Oh no, what I'm holding is nothing.
Well, look who finally decided to pick up the phone.
The t-shirt told me to 'Just Do It.' I don't know what 'it' refers to!
I will not be spoken to in that tone by an article of clothing!
You don't know how lucky you are to have me!
You can fill your life with projects, books, movies and your little girlfriends, but it won't make you whole.
You're an idiot, there's no cure for that!
When are you going to come visit me? And bring me some carrot cake.
You could be thin. Just go easy on the sweets, and when you go somewhere, don't walk, gallop!
You know, nobody gives a daOn what you feel!
Don't believe all that crOp all your big Hollywood agents tell you.
You know, I remember when your father Butterscotch first saw you after you were born -- he thought you'd have a racing career.
You're just like your father.
This rest home is a shOt hole. Don't forget that I was heiress to the Sugarman Sugar Cube fortune and I'm accustomed to a certain lifestyle.
I forget, did I have another child besides you? Or was that just a wish?
So did that vending machine I bought you work out? Or did you wash down every carrot with beer?
Why doesn't Butterscotch come visit me?
Are you still hanging around with those same loser friends of yours?
You're so lucky to have had me as your mother. My own mother was never the same after her lobotomy...
I remember when you thought you'd try playing football. You didn't have the haunches for it.
I should have married Corbin Creamerman instead of your father. How my life would have been different...
Everything they serve here at the nursing home tastes like moldy hay.
Are you playing a video game right now?
You know, my parents never let me eat ice cream. They only let me have sugar coated lemon wedges.
Are you still playing with sea horses?
Have you ever even watched my TV show?
Don't make fun of my seahorses!
It's not like when I was a child and had sea monkeys...
You know, I am not a LOSER! I played Secretariat!!!
No, I don't sound like Mr. Ed! He WAS a LOSER!


Homework Answers

Answer #1

Please find the requested program and the sample input files I have used for testing. Also attaching the screenshot of the output and the screenshot of the partial code to understand the code intendation.

Please provide your feedback

Thanks and Happy learning!

Output:

#include<vector>
#include<iostream>
#include<fstream>
#include <string>
#include <sstream>
#include <stdlib.h>
#include <time.h>
#include <ctype.h>

//Function which reads an input file line by line and stores
//each line in a vector and return the vector
void  ReadInputFromFile(std::string strFilename, int& lineCount, std::vector<std::string>& outVector)
{
    std::vector<std::string> lines;
    std::ifstream inFile;
    inFile.open(strFilename, std::ifstream::in);

    //Check if input file is opened successfully
    if (inFile.is_open())
    {
        std::string strLine;
        bool bFirstLine = true;
        //Read each line from input file one after another
        while (std::getline(inFile, strLine))
        {
            if (bFirstLine)
            {
                std::stringstream ss;
                ss << strLine;
                ss >> lineCount;
                bFirstLine = false;
            }
            outVector.push_back(strLine);
        }

        //Close the file
        inFile.close();
    }
    else
    {
        std::cout << "ERROR: Could not open file :" << strFilename << std::endl;
    }
}

void writeToOutFile(const std::string& strFileName, const std::vector<std::string>& dialoguesToBeWritten)
{
    std::ofstream outFile;
    outFile.open(strFileName, std::ifstream::out);
    //Check if input and output files are opened successfully
    if (outFile.is_open())
    {
        //Write the result to the output file
        for (int i = 0; i < dialoguesToBeWritten.size(); i++)
        {
            outFile << dialoguesToBeWritten[i] << std::endl;
        }

        outFile.close();
        std::cout << "Output file has been written successfully to the current working directory." << std::endl;
    }
    else
    {
        std::cout << "ERROR: Could not open file :" << strFileName << std::endl;
    }
}

void SanitizeDialogue(std::string& strCurrentDialogue, const std::string& badWord, std::string goodWord)
{
    std::size_t foundPos = strCurrentDialogue.find(badWord);
    while (foundPos != std::string::npos)
    {
        //If the "bad" word begins with an uppercase letter in the saying, then the "good" 
        //word it is replaced with must also begin with an uppercase letter in the saying.
        if (isupper(badWord[0]))
        {
            toupper(goodWord[0]);
        }
        strCurrentDialogue.replace(foundPos, badWord.length(), goodWord);

        foundPos = strCurrentDialogue.find(badWord);
    }
}

void Sanitize(std::string& strCurrentDialogue)
{
    //Each "bad" word is to be replaced with a "good" word.
    //Here's how they are to be replaced:
    //
    // idiot - > mean person
    // dammit - > darn it
    // shOt - > poop
    // crOp - > poopie
    // daOn - > hoot
    std::string strBadWord = "idiot";
    std::string strGoodWord = "mean person";
    SanitizeDialogue(strCurrentDialogue, strBadWord, strGoodWord);

    strBadWord = "dammit";
    strGoodWord = "darn it";
    SanitizeDialogue(strCurrentDialogue, strBadWord, strGoodWord);

    strBadWord = "shOt";
    strGoodWord = "poop";
    SanitizeDialogue(strCurrentDialogue, strBadWord, strGoodWord);

    strBadWord = "crOp";
    strGoodWord = "poopie";
    SanitizeDialogue(strCurrentDialogue, strBadWord, strGoodWord);

    strBadWord = "daOn";
    strGoodWord = "hoot";
    SanitizeDialogue(strCurrentDialogue, strBadWord, strGoodWord);
}


int main()
{
    int dialogueCount_Hans;
    std::vector<std::string> HansDialogues;

    ReadInputFromFile("Hans.dat", dialogueCount_Hans, HansDialogues);

    int dialogueCount_Beatrice;
    std::vector<std::string> BeatriceDialogues;

    ReadInputFromFile("Beatrice.dat", dialogueCount_Beatrice, BeatriceDialogues);

    std::vector<std::string> SanitizedDialogueToBeWrittenToOutFile;

    std::cout << "Hans> Hello" << std::endl;
    SanitizedDialogueToBeWrittenToOutFile.push_back("Hans> Hello");

    int maxDialogueCount = 20;
    int currentDialogueCount = 0;
    
    //A flag to decide whom should speak next
    bool bHansTurn = false;

    //initialize random seed
    srand(time(NULL));

    std::string strCurrentDialogue;
    std::string strPrompt;
    while (currentDialogueCount < maxDialogueCount)
    {
        if (bHansTurn)
        {
            bHansTurn = false;
            //Generate a random number to select a random dialoge from the Hans dialogue list.
            //Generate random number between 0 and dialogueCount_Hans - 1
            int iRandomIndex = rand() % (dialogueCount_Hans - 1);

            strCurrentDialogue = HansDialogues[iRandomIndex];

            Sanitize(strCurrentDialogue);
            strPrompt = "Hans> ";
        }
        else
        {
            bHansTurn = true;
            //Generate a random number to select a random dialoge from the Beatrice dialogue list.
            //Generate random number between 0 and dialogueCount_Beatrice - 1
            int iRandomIndex = rand() % (dialogueCount_Beatrice - 1);

            strCurrentDialogue = BeatriceDialogues[iRandomIndex];

            Sanitize(strCurrentDialogue);
            strPrompt = "Beatrice> ";
        }

        //Print the sanitized dialogue to the screen
        strCurrentDialogue = strPrompt + strCurrentDialogue;
        std::cout << strCurrentDialogue << std::endl;

        //Increment the dialogue count
        ++currentDialogueCount;

        SanitizedDialogueToBeWrittenToOutFile.push_back(strCurrentDialogue);       
    }

    std::cout << "Hans> goodbye" << std::endl;
    SanitizedDialogueToBeWrittenToOutFile.push_back("Hans> goodbye");

    std::cout << "Beatrice> goodbye" << std::endl;
    SanitizedDialogueToBeWrittenToOutFile.push_back("Beatrice> goodbye");

    writeToOutFile("Conversation.dat", SanitizedDialogueToBeWrittenToOutFile);

    getchar();
    return 0;
}

Hans.dat

25
Mother, why are you such an idiot?
You know, I remember when you tried to drown me in the bathtub when I was 22!
Do you need me to donate blood for you again?
idiot, idiot, idiot!
Dammit, mother! Why do you keep bringing that up?
Mother, Butterscotch has been dead for years.
Oh, that's just a bunch of crOp!
You're full of shOt!
Do you need your teeth filed? Your tongue has certainly gotten sharp!
You know, I might call you more often if you'd say nice things to me!
Nag, nag, nag!
Oh, geez. Give it a rest!
Dammit, don't you have anything nice to say?
Have you been drinking?
Why can't you be proud of my acting career?
I don't mean to be indelicate, but when was the last time you were de-wormed?
Are you taking your medications?
You know, eating hay might help keep your regular.
Did the glue factory people stop calling you?
Saying things like that hurts my feelings...
Oh, big stud! Always running around to gallivant with your fillies!
Remember, don't sit too close to the TV, it will make you cruel!
You know, I was beautiful before I had you.
I'm sorry, did you need a compliment?
Oh, this letter I have? It's from the government saying I'm proud of you!

Beatrice.dat

30
Oh no, what I'm holding is nothing.
Well, look who finally decided to pick up the phone.
The t-shirt told me to 'Just Do It.' I don't know what 'it' refers to!
I will not be spoken to in that tone by an article of clothing!
You don't know how lucky you are to have me!
You can fill your life with projects, books, movies and your little girlfriends, but it won't make you whole.
You're an idiot, there's no cure for that!
When are you going to come visit me? And bring me some carrot cake.
You could be thin. Just go easy on the sweets, and when you go somewhere, don't walk, gallop!
You know, nobody gives a daOn what you feel!
Don't believe all that crOp all your big Hollywood agents tell you.
You know, I remember when your father Butterscotch first saw you after you were born -- he thought you'd have a racing career.
You're just like your father.
This rest home is a shOt hole. Don't forget that I was heiress to the Sugarman Sugar Cube fortune and I'm accustomed to a certain lifestyle.
I forget, did I have another child besides you? Or was that just a wish?
So did that vending machine I bought you work out? Or did you wash down every carrot with beer?
Why doesn't Butterscotch come visit me?
Are you still hanging around with those same loser friends of yours?
You're so lucky to have had me as your mother. My own mother was never the same after her lobotomy...
I remember when you thought you'd try playing football. You didn't have the haunches for it.
I should have married Corbin Creamerman instead of your father. How my life would have been different...
Everything they serve here at the nursing home tastes like moldy hay.
Are you playing a video game right now?
You know, my parents never let me eat ice cream. They only let me have sugar coated lemon wedges.
Are you still playing with sea horses?
Have you ever even watched my TV show?
Don't make fun of my seahorses!
It's not like when I was a child and had sea monkeys...
You know, I am not a LOSER! I played Secretariat!!!
No, I don't sound like Mr. Ed! He WAS a LOSER!
Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Identify the sender's communication ego state: A. CP - Critical ParentB. SP - Sympathetic Parent C....
Identify the sender's communication ego state: A. CP - Critical ParentB. SP - Sympathetic Parent C. NC - Natural Child D. AC - Adapted Child E. A - Adult 1A) 1. "A good boss wouldn't make me do it" 2. "I'm always willing to help you out, Ted." 3. "I'm not cleaning that up." 4. "You're not being serious, are you?" 5. "Ill get right on it." 2A) 1. It's not my fault. I didn't clean it personally." 2. I'm...
If two parallel wires have current running in the same direction, do the wires attract each...
If two parallel wires have current running in the same direction, do the wires attract each other or repel each other due to their magnetic interaction? My attempt so far: I'm imagining two parallel wires oriented vertically with the current flowing "downwards" (in the negative y direction) in each. In this case, I believe there's a circular magnetic field that wraps around and surrounds each respective wire in the clockwise direction (when looking directly downwards at each wire). Can you...
please answer and explain Video Transcript: Promoting Children's Health: A Focus on Nutrition in Early Childhood...
please answer and explain Video Transcript: Promoting Children's Health: A Focus on Nutrition in Early Childhood Settings: >> Our most important job is to keep the children safe and healthy. And within keeping them healthy and keeping them safe, we want to make sure that they are receiving proper nutrition. So at this age, starting healthy habits, we want to make sure that the preschool and kindergarten age children are receiving all that we can give them when it comes...
John and Marsha on Portfolio Selection The scene: John and Marsha hold hands in a cozy...
John and Marsha on Portfolio Selection The scene: John and Marsha hold hands in a cozy French restaurant in downtown Manhattan, several years before the mini-case in Chapter 9. Marsha is a futures-market trader. John manages a $125 million common-stock portfolio for a large pension fund. They have just ordered tournedos financiere for the main course and flan financiere for dessert. John reads the financial pages of The Wall Street Journal by candlelight. John: Wow! Potato futures hit their daily...
the following list of fallacies examined in the question Ad hominem Composition Illicit appeal to authority...
the following list of fallacies examined in the question Ad hominem Composition Illicit appeal to authority Appeal to the few Appeal to a saying Appeal to Ignorance Appeal to novelty Appeal to tradition Bad ANALOGY Bandwagon Begging the question Circular argument Division Equivocation False alternative False cause False disjunct Genetic Fallacy Half-truth Hasty generalization Irrelevant reasons Leading question Lifting out of context Question begging definition Red herring Slippery slope Straw man Weasel words Here is the Question Identify the logical...
Forest Fires By Sarah Kay 2010 I arrive home from JFK in the rosy hours to...
Forest Fires By Sarah Kay 2010 I arrive home from JFK in the rosy hours to find a brand new five-in-one egg slicer and dicer on my dining room table. This is how my father deals with grief. Three days ago, I was in the Santa Cruz redwoods, tracing a mountain road in the back of a pickup truck, watching clouds unravel into spider webs. Two days from now, there will be forest fires so thick, they will have to...
3.5 Being Friendly versus Being Friends for Difficult Conversations Kasper Rorsted, chief executive of Henkel, the...
3.5 Being Friendly versus Being Friends for Difficult Conversations Kasper Rorsted, chief executive of Henkel, the consumer and industrial products company based in Dusseldorf, Germany, recently talked about the first time he had to be someone else's boss: "[I first became someone else's boss] in 1989, right when I got promoted from being a sales rep in the Digital Equipment Corporation to being a sales manager at the age of 27. I had about 20 people at that point in...
Textbook: Spiker Taxation of Individuals Comprehensive Problem 6-68 (LO 6-1, LO 6-2, LO 6-3) [The following...
Textbook: Spiker Taxation of Individuals Comprehensive Problem 6-68 (LO 6-1, LO 6-2, LO 6-3) [The following information applies to the questions displayed below.] Read the following letter and help Shady Slim with his tax situation. Please assume that his gross income is $172,900 (which consists only of salary) for purposes of this problem. December 31, 2017 To the friendly student tax preparer: Hi, it’s Shady Slim again. I just got back from my 55th birthday party, and I’m told that...
For this Discussion, review the client in the case study within the Learning Resources. Consider symptoms...
For this Discussion, review the client in the case study within the Learning Resources. Consider symptoms or signs presented by the client for a diagnosis. Think about how you, as a future professional in the field, might justify your rationale for diagnosis. Consider what other information you may need for diagnosis on the basis of the DSM diagnostic criteria. FEMALE SPEAKER: Well, I just keep thinking what if something happens? I mean I've always had trouble concentrating. But this time,...
Kirby walked into Nancy’s office and said, “I need to talk to you.” He then closed...
Kirby walked into Nancy’s office and said, “I need to talk to you.” He then closed the door and said, “I didn’t appreciate it when you challenged my new production scheduling plan in the meeting. If you had real concerns, why didn’t you wait to talk to me in private? It’s embarrassing to have someone trash my ideas and I don’t want it to happen again.” Nancy, taken by surprise by Kirby’s response replied, “Well, I’m sorry if I embarrassed...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT