I've got this kind of problem, where I want to change a word inside of a text file.
apparently, I can use the char to change the character, however, it can't changes any word or sentence, so can any one help me out. much appreciated.

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

int main(){

    ifstream fin;
	ofstream fout;

	if (fin.fail()){
	cout << "open failed!";
    if (fout.fail()){
	cout << "save failed!";
     char next, key;
	cin >> key;
	do {
       fin >> next;
	   if (next == '2')
	       fout << '0';
		   fout << next;
	}while (!fin.eof());

   cout << "end of the program.";
 cin.ignore(1000, '\n'); // clear out any additional input from the stream   
   return 0;

To change words/lines in a text file you need to delete the original file then write a new one with the changes.

Use std::strings to make it easier to change words/lines.

This example will read each word from a file, allow you to make the changes you want, and then write them back. The only problem with this example is that all indentation and extra spaces will be lost. To do it properly, you will have to load the entire file into a string, and make the changes manually.

using namespace std;

const char fileName[] = "test.txt";

int main() {
	ifstream in(fileName);
	string word;
	vector<string> words;

	while (in >> word) {

	/* Make changes */

	ofstream out(fileName);

	size_t size = words.size();

	for (size_t i = 0; i < size; ++i) {
		out << words[i] << ' ';

	return 0;

Hope this helps.

This article has been dead for over six months. Start a new discussion instead.