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?).