Hello,
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;

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

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

Recommended Answers

All 2 Replies

Member Avatar for iamthwee

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.

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

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

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

	while (in >> word) {
		words.push_back(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.

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.