I am trying to write a program in which a big text file is read and then user searches for a word and replaces it with another word. To implement this I was thinking to store the file read into an array since that would the easiest way to implement it (as far as I Know) and then compare each element with the word to be searched and when found replace it.
Here is my code:

#include<iostream>
#include<fstream>
#include<string>
using namespace std;

int main()
{
    ifstream insert;
    ofstream output;
   
    string lineread;
   
    insert.open("test.txt");
   
    if(insert.fail())
    {
        cout<<"File failed to open"<<endl;
        }
       
        while(!insert.eof())
        {
          getline(insert,lineread);
          cout<<lineread<<endl;//test to see if it prints the right text file
          }
 
    system("PAUSE");
    return (0);

As you can see I have used a string variable to store the file being read but I want it to be stored in array which I don't understand how to implement.
I thought of using pointer arrays or better dynamic arrays but I am not able to implement it. Also I have looked up the pop and stack functions but I haven't been taught that so I am not very sure to use them.

Besides that any help is appreciated

Recommended Answers

All 7 Replies

I am trying to write a program in which a big text file is read and then user searches for a word and replaces it with another word. To implement this I was thinking to store the file read into an array since that would the easiest way to implement it (as far as I Know) and then compare each element with the word to be searched and when found replace it.
Here is my code:

If the program simply reads in a file and replaces all instances of "dog" with "cat" or something, and writes it to a new file, I see no need to actually STORE the contents of the file in memory. Get a line from the ifstream and read it into a string. Replace all instances of "dog" in that line with "cat". Output the revised line to the ofstream. No need to store anything as far as I can tell.

If you decide you DO want to store the lines in an array, your main problem is the problem of not knowing how many lines there are in advance. Solve it by either:

  1. Go through the file and count the number of lines, size your string array to that size, then open the file again and go through it line by line, substituting.
  2. Decide on a maximum number of lines in the file and make that the size.
  3. Guess the size ahead of time, resize as you go through the file if your guess is incorrect.
  4. Use a vector instead of an array, in which case this is all done for you.
  5. Use something besides an array or vector (i.e. linked list) that avoids the overhead and guesswork of resizing.

If the program simply reads in a file and replaces all instances of "dog" with "cat" or something, and writes it to a new file, I see no need to actually STORE the contents of the file in memory. Get a line from the ifstream and read it into a string. Replace all instances of "dog" in that line with "cat". Output the revised line to the ofstream. No need to store anything as far as I can tell.

If you decide you DO want to store the lines in an array, your main problem is the problem of not knowing how many lines there are in advance. Solve it by either:

  1. Go through the file and count the number of lines, size your string array to that size, then open the file again and go through it line by line, substituting.
  2. Decide on a maximum number of lines in the file and make that the size.
  3. Guess the size ahead of time, resize as you go through the file if your guess is incorrect.
  4. Use a vector instead of an array, in which case this is all done for you.
  5. Use something besides an array or vector (i.e. linked list) that avoids the overhead and guesswork of resizing.

Thats an interesting point of view. I guess I wasn't thinking the right way. Thanks for the idea, I may try that way.

Ok I am almost done with this program except for the replace part. Here is my code so far:

#include<iostream>
#include<fstream>
#include<string>
#include<iomanip>
using namespace std;

int main()
{
    ifstream insert;
    ofstream output;
     
    string lineread; //line read  from the text file
    char* search; //the word to be searched
    char* replace; //the word to be replaced
    int position;

    insert.open("test.txt");
    
    if(insert.fail())
    {
        cout<<"File failed to open"<<endl;
        }
        
        //while(!insert.eof())
        {
          getline(insert,lineread); 
          cout<<lineread<<endl;//test to see if it prints the right text file
          }
          
          cout<<" Enter the word to be searched."<<endl;
          cin>> search;
          
          if((position = lineread.find(search,0)) != string::npos)
          {
            cout<<"The word:"<<search<<": was found"<<endl;
            cout<<"Replace this word with"<<endl;
            cin>>replace;
            
            cout<<lineread<<endl;
}          
  system("PAUSE");
    return (0);
}

Can you give some idea as to how can I replace the word with the new word.
This is what I was thinking to do but not really able to implement it.
1) My variable that stores the word to be searched is a pointer variable.
2) So if I could using the address of the variable I could put in a new word in that place.
Am I thinking it the right way? Either way please let me know how would I implement it.
Thanks.

I think you want to write this function:

string ReplaceWords (string line, string wordToReplace, string replaceWith)
{
    while (/* find next instance of word to replace */)
    {
        // replace this instance of the word
    }
    
    return line;
}

find and replace from string will be useful.

From main:

string wordToReplace, replaceWith;

// read above variables from user
// open file

while (/* more lines in file */)
{
    // read a line from ifstream
    // call function above to alter that line
    // output altered line to ofstream
}

I finally realized that I can use a temp variable to replace the word (I dunno what was I thinking until now!) But now I don't know how will I put the replaced word back into the sentence.
I mean, for example: I have a sentence ( teh disability documents....) where I want to replace 'teh' with 'the', now after replace this word how do I put it back into the sentence. Here is my code:

#include<iostream>
#include<fstream>
#include<string>

using namespace std;

string ReplaceErr(string, string, string);


int main()
{
    
    ifstream insert;
    ofstream output;
    
    string Line, WordToRep, RepWith, ReadLine; 
    
    insert.open("test.txt");
    
    if(insert.fail())
    {
        cout<<"File failed to open"<<endl;
        }
        //while(!insert.eof())
        
        getline(insert,ReadLine);
        cout<<ReadLine<<endl; //ReadLine will store the whole line read from the file
        
        
        cout<<"Please enter the word to be replaced."<<endl;
        cin>> WordToRep;
        
        ReplaceErr(ReadLine, WordToRep,RepWith);
        

system("Pause");       
return 0;
}

 string ReplaceErr(string RL, string  W2R, string RW) //RL = ReadLine, W2R = WordToReplace, RW = ReplaceWith
 {
        
        int position;
        string newWord; //temporary variable to store the word to replace with
        
        if((position = RL .find(W2R,0)) != string::npos)
        {
          cout<<"The word to be replaced:"<<W2R<<"was found."<<endl;
          }
          
          cout<<"Please enter the word to replace with."<<endl;
          cin>>RW;
          
          newWord = W2R;
          W2R = RW;

return RL;
}

Thanks.

If I understand what the goal of this, it's to do something like this with a file (below):

My dog has fleas.
I need to take my dog to the vet.
My dog doesn't get along with other dogs.
I took my dog to the dog park to play with the other dogs.

Replace "dog" with "cat". Resulting file:

My cat has fleas.
I need to take my cat to the vet.
My cat doesn't get along with other cats.
I took my cat to the cat park to play with the other cats.

If that's what you are trying to do, i don't see any reason to have a cin statement (or a cout statement) in any function. I think you should have all cout and cin statements before opening either file (don't have any in any loop or replacement function) and go with the skeleton in my previous post. In particular, why ask what the replacement word is when you've already passed it to the function?

Line 40 - RepWith is passed to the function by value, so it better be initialized before you call that function (it isn't). Why overwrite it in line 52?

Line 33 - As mentioned, RepWith is uninitialized. Pass-by-value parameters should be initialized.

See my prior post.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.