mohsen
mohsen

Reputation: 17

How to copy a file into another file but replace a word with a user entered word?

I am trying to copy a file to another file, but change a word with what the user has entered. So far I have come up with this:

while (getline(openningTheFile, line, ' ')) //line is a string and openningTheFile is an ifstream 
{
    if (line == wordToBeDeleted)
    {
        line = wordToReplaceWith;

    }
    if (line == "\n")
    {
        newFile << endl; //newFile is an ofstream 
    }

    newFile << line << " ";
}

But the problem is that this code does not read the word after the "\n" because the delimiter is spaces.

Could anyone point me in the right direction?

Upvotes: 1

Views: 93

Answers (4)

zett42
zett42

Reputation: 27766

Here is a solution that uses the power of boost::iostreams to solve the task in a high level but still very flexible way.

For OP's case this is propably like using a sledge hammer to crack a nut, but if one needs flexibility or has to deal with more complex cases, it might be the right tool.

I'm using a filtering stream combined with a regular expression. This allows us to replace a search pattern with a substitution string on-the-fly, without creating any intermediate string.

#include <iostream>
#include <string>
#include <sstream>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/regex.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/regex.hpp>
namespace io = boost::iostreams;
using namespace std;

int main()
{ 
    // Your input "file" - you may replace it by an std::ifstream object.
    istringstream in( "why waste time learning learninglearning, when ignorance is instantaneous?" );

    // Search pattern and substitution string.        
    string findRegEx( R"(\blearning\b)" );
    string replaceStr( "sleeping" );

    // Build a regular expression filter and attach it to the input stream.
    io::filtering_istream inFiltered;
    inFiltered.push( io::regex_filter( boost::regex( findRegEx ), replaceStr ) );
    inFiltered.push( in );

    // Copy the filtered input to the output, replacing the search word on-the-fly.
    // Replace "cout" by your output file, e. g. an std::ofstream object.
    io::copy( inFiltered, cout );

    cout << endl;
}

Live demo

Output:

why waste time sleeping learninglearning, when ignorance is instantaneous?

Notes:

  • The actual regular expression is \blearning\b
  • We don't need to escape the backslash because we are using a raw string literal. Very neat for stuff like this.
  • The regular expression searches for the whole word "learning" (\b denotes a word boundary). That's why it only replaces the first occurence of "learning" and not "learninglearning".

Upvotes: 0

R Sahu
R Sahu

Reputation: 206607

Strategy I recommend:

  1. Read the file line by line using std::getline.
  2. Look for the string that you would like to replace in the line using std::string::find.
  3. If it is found, replace it with the new string.
  4. Repeat steps 2 and 3 until the string is not found.
  5. Output the updated line.

Here's the core code for that:

while (getline(openningTheFile, line)) 
{ 
   std::string::size_type pos;
   while ( (pos = line.find(wordToBeDeleted)) != std::string::npos )
   {
      line.replace(pos, wordToBeDeleted.length(), wordToReplaceWith);
   }
   newFile << line << '\n';
}

Upvotes: 3

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

You can do that by modifying the loop to read word-wise from the line read using std::istringstream:

while (getline(openningTheFile, line)) 
{ 
    std::istringstream iss(line);
    std::string word;
    bool firstWord = true;
    while(iss >> word)
    {
        if(word == wordToBeDeleted) {  
            newFile << wordToReplaceWith;
            if(!firstWord) {
                newFile << " ";
            }
            firstWord = false;
        }
    }
    newFile << `\n`;
}

Upvotes: 0

Thomas Matthews
Thomas Matthews

Reputation: 57698

You are reading a line of text with std::getline.

You will need to find the word within the text line, replace the word, then write the text line to the output file.

One method is to use std::stringstream and operator >> to extract the word from the string.

Another is to use std::string::find to locate the position of the word.

Upvotes: 0

Related Questions