SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,kenrick Mock
Chapter:
Flow Of Control
Exercise:
Programming Projects
Question:10 | ISBN:9780132846813 | Edition: 5

Question

Create a text fi le that contains the text “I hate C++ and hate programming!” Write a program that reads in the text from the fi le and outputs each word to the console but replaces any occurrence of “hate” with “love.” Your program should work with any line of text that contains the word “hate,” not just the example given in this problem.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

//Include header files
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

//main function
int main( )
{
    
    string inputText;
    fstream inputFile;
    //Open input file data
    inputFile.open("file.txt");
    //Replaces any occurrence of “hate” 
    //with “love.”
    while (inputFile >> inputText)
    {
        if (inputText == "hate")
            cout << "love ";
        else
            cout << inputText << " ";
    }
    inputFile.close();
    cout << endl;
}

file.txt data:

I hate C++ and hate programming!

Output of the program code:

I love C++ and love programming!

 

0 0

Discussions

Post the discussion to improve the above solution.