Thread: Find and replace

  1. #1
    Registered User
    Join Date
    Sep 2005
    Posts
    35

    Find and replace

    Ok, I have 2 option boxes and a button (see attached file).

    http://www.wdtalk.net/findandreplace.zip

    This is what I want: option 1 is linked to c:\file1.txt and option2 is linked to c:\file2.txt

    file1 contains the following text: "Hello world, how are you?". When option 1 is ticked and you click the button it searches for "world" in the txt file and changes it to "Bob".

    file2 contains the following text: "I like melon". When option 2 is ticked and you click the button it searches for "melon" in the txt file and changes it to "potatoes".

    How can I make something like this?

    All help is really appreciated!

    Kindest regards and thanks in advance,

    Sam Granger

  2. #2
    Super Moderater.
    Join Date
    Jan 2005
    Posts
    374
    Perusing through some of the previous threads I found this snippet:

    Code:
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    int main()
    {
        string search ("Hello world how are you?");
        cout<<search;
        char word[81];
        cout<<"\n\nPlease enter the word you wish to replace\n>>";
        cin>>word;
        int size = strlen(word);
        cout<<"\n\nWhat word do you wish to replace it by\n>>";
        
        char r_place[81];
        cin>>r_place;
        
        
        
    	
    	string::size_type pos = -1;
    	while( ( pos = search.find(word, pos+1) ) != string::npos )
    	{
    		search.erase( (search.begin() + pos), (search.begin() + (pos + size)) );
    		search.insert( pos, r_place );
    	}
    	cout << search << endl;
    	cin.get();
    	cin.get();
    	return 0;
    }

    My sample input:
    Code:
    Hello world how are you?
    
    Please enter the word you wish to replace
    >>world
    
    
    What word do you wish to replace it by
    >>bob
    My sample output:
    Code:
    Hello bob how are you?

    This code should be easy to adapt to handle text files. And then to finally incorporate in your win32 application, I assume. I hope this is useful.
    Last edited by treenef; 10-07-2005 at 11:39 AM.

  3. #3
    Registered User
    Join Date
    Sep 2005
    Posts
    35
    Hey treenef!

    Thanks for the code! I'm going to try and get it to work for a text file!

    Thanks again!

  4. #4
    Registered User
    Join Date
    Sep 2005
    Posts
    35
    Damn.

    I can't get this to work.

  5. #5
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    You can't get treenef's to work?

    BTW, strlen() is in <cstring>.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  6. #6
    Super Moderater.
    Join Date
    Jan 2005
    Posts
    374
    What are you having problems with. The actual code provided or getting the code to work with text files, or getting the code to work with your win32 application?


    I suggest doing it in steps. Try to get the code to work with files. If that works then try incorporating it into your win32 application.

    If you have any problems post them here. But try to be specific as to what you problem is, and if you are getting compiler errors post them here too.


  7. #7
    Registered User
    Join Date
    Sep 2005
    Posts
    35
    I'm not sure how to link it to files.

  8. #8
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    "linking" to files is usually (there may be other ways) done by passing the file name (or full path name of the file) to the constructor of a filestream or to the open() method of a file stream. For example:

    ifstream fin("myfile.txt");

    or

    ifstream fin;
    fin.open("myfile.txt");

    Both syntax will open myFile.txt file using the ifstream fin assuming myFile.txt is in the working directory. If myFile.txt is not in the working directory, then you need to enter the full path name (using \\ instead of \ if necessary in the path name) rather than just the file name and extension.
    You're only born perfect.

  9. #9
    Super Moderater.
    Join Date
    Jan 2005
    Posts
    374
    Just to echo what elad said you may want to look at this

    http://www.cprogramming.com/tutorial/lesson10.html

    My advice would be to play around with this to make sure you understand how to handle reading and writing to files. Then you can go about incorporating the code I have already provided into your program.

    The only stumbling block I can see, is trying to preserve the formating of the original file. However, we can deal with that when you have tried this?

  10. #10
    Registered User
    Join Date
    Sep 2005
    Posts
    35
    Code:
    //---------------------------------------------------------------------------
    
    #include <vcl.h>
    #include <fstream>
    #include <iostream>
    
    //---------------------------------------------------------------------------
    
    using namespace std;
    
    int main()
    {
      char str[10];
    
      //Creates an instance of ofstream, and opens example.txt
      ofstream a_file ( "example.txt" );
      a_file<<"This text will now be inside of example.txt";
      // Close the file stream explicitly
      a_file.close();
      cin.get();    // wait for a keypress
      // b_file is closed implicitly here
    }
    //---------------------------------------------------------------------------
    Got this so far which adds the text to a txt. How do I make this code find and replace text in the txt file?

  11. #11
    Registered User
    Join Date
    Aug 2005
    Posts
    13

    files passed to the program

    My question is simliar to the contex of this post. I understand acutally "hard coding" the address of the file you want to open in your program but what about when you don't know where the file is when your program is run. For example when I double click on a text file in windows it runs notepad. That file can be located anywhere so your program does't know where it is. Not knowing a lot about windows programming I assume that windows somehow passes the location of the file to your program. I'm just wondering how you set up your program to get that information from the OS

  12. #12
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    The example you cited uses the registry. Text files are usually associated (or "registered") with notepad. When you click on a file of a type that's associated with an application in Windows, Window's starts that application, and passes the file as a parameter to that program (e.g. in a console window, this would look like, "notepad myfile.txt"). In your program, you can recieve these parameters as though they were passed to your main function. If you want to use this feature, your main prototype should look like this:
    Code:
    int main(int argc, char *argv[])
    argv is an array of pointers to strings, where each string is one of the tokens entered at the command line, so argv[0] points to a string that is the name of the program, argv[1] points to the first parameter, and so forth. argc is the number of elements in that array.

    As for getting your program to use the registry like your notepad example, I wouldn't recommend messing with the registry until you're more experienced with Windows Programming.

  13. #13
    Super Moderater.
    Join Date
    Jan 2005
    Posts
    374
    Ok that's good. So you know how to write to a file. Next you will need to read from a file.

    The idea with a replace word program is as follows.

    1. Read the original file in, probably one line in at a time to preserve it's format.

    2. Create another file, for example "update.txt". Now you would write the original file plus the change of word to update.txt.

    It's as simple as that.

    The question you are probably wondering is how do you read a line in from a text file: In your case you should probably read the file in as a string. Like in the example I have shown above.


    Code:
    #include <iostream> //for basic input output
    #include <string>     //to use the commands for strings
    #include <fstream>  //to handle writing and reading from files
    
    using namespace std;
    int main()
    {
       ifstream f_in  ("example.txt");
       string line;
       
       while(getline(f_in, line, '\n'))
       {
        
        //put my original snippet here.
        cout<<line<<"\n";
       }
       f_in.close();
      cin.get();
      cin.get();
    } 
    }


    Let me just explain a few things here.

    Code:
    while(getline(f_in, line, '\n'))
    The getline is a function you can use for strings which reads all the information until it gets to a newline i.e '\n'. And then repeats until it gets to the end of the file.

    So for example, let's say you wanted to read in the file as words rather than lines you would change is to.

    Code:
    while(getline(f_in, line, ' '))
    Since a word is normally defined as being separated by a white space.

    Have a go see how far you get then post your problems here.

    The getline function has the advantage that it preserves the formating of the original file. In other words it doesn't skip over whitespaces unless you want it to. It can only be used for strings though and not char arrays (I think, I may be wrong?).
    Last edited by treenef; 10-18-2005 at 05:57 AM.

  14. #14
    Registered User
    Join Date
    Sep 2005
    Posts
    35
    Hmm, what am I doing wrong here.

    Code:
    //---------------------------------------------------------------------------
    
    #include <vcl.h>
    #include <fstream>
    #include <iostream>
    
    //---------------------------------------------------------------------------
    
    using namespace std;
    int main()
    {
       ifstream f_in  ("example.txt");
       string line;
    
       while(getline(f_in, line, '\n'))
       {
    
            string search ("This text will now be inside of example.txt");
        cout<<search;
        char word[81];
        cout<<"\n\nPlease enter the word you wish to replace\n>>";
        cin>>word;
        int size = strlen(word);
        cout<<"\n\nWhat word do you wish to replace it by\n>>";
        
        char r_place[81];
        cin>>r_place;
        
    
    
    
    	string::size_type pos = -1;
    	while( ( pos = search.find(word, pos+1) ) != string::npos )
    	{
    		search.erase( (search.begin() + pos), (search.begin() + (pos + size)) );
    		search.insert( pos, r_place );
    	}
    	cout << search << endl;
        cout<<line<<"\n";
       }
       f_in.close();
      cin.get();
      cin.get();
    }
    
    //---------------------------------------------------------------------------
    Thanks for all the help so far btw!

  15. #15
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Code:
    char word[81];
    cout<<"\n\nPlease enter the word you wish to replace\n>>";
    cin>>word;
    int size = strlen(word);
    cout<<"\n\nWhat word do you wish to replace it by\n>>";
        
    char r_place[81];
    cin>>r_place;
    Why don't you just keep using strings instead of switching between C++ strings and C-style character string?




    Code:
    search.erase( (search.begin() + pos), (search.begin() + (pos + size)) );
    search.insert( pos, r_place );
    There is a replace member function for the string container that will eliminate one line of code.

    Code:
    search.replace(pos,size,r_place);
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to find and replace a string in a file
    By salzouby in forum C Programming
    Replies: 13
    Last Post: 09-14-2010, 08:55 AM
  2. Find and replace within a string?
    By clancyPC in forum C Programming
    Replies: 3
    Last Post: 03-20-2009, 07:28 AM
  3. please help!...find and replace
    By amy589 in forum C++ Programming
    Replies: 26
    Last Post: 10-13-2006, 06:42 PM
  4. Find and replace
    By BobDole1 in forum C++ Programming
    Replies: 1
    Last Post: 04-12-2003, 10:06 PM
  5. Find and Replace Text Function
    By mart_man00 in forum C Programming
    Replies: 45
    Last Post: 03-13-2003, 10:21 PM