Friday, 22 January 2016

C Plus Plus Program to Replace a specified Line in a Text File - cppexamples

Leave a Comment
Questions:

C Plus Plus Program to Replace a specified Line in a Text File

Explanation:

This C Plus Plus Program to Replace a specified Line in a Text File,

Code:

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void main() {

       fstream file;//creating txt file
       file.open("Reading.txt",ios::in); //opening file in reading mod Reading.txt file is located in your project foler
       int temp2 = 0;
       cout << "Data In Reading File" << endl;
       while (file) {
              string temp;
              getline(file, temp);
              temp2++;
       }
       cout << endl << endl;
       string *data = new string[temp2];
       temp2 = 0;
       file.close();
       file.open("Reading.txt", ios::in);
       cout << endl << endl << endl;
       while (file) {
              string temp;
              getline(file, temp);
              cout <<temp2+1<<"  "<< temp << endl;
              data[temp2] = temp;
              temp2++;
       }
       file.close();

       //writing data on file
       string data2;
       string data3;
       cout << "Enter Data that you want to replace == ";
       getline(cin, data2);
       cout << "Enter Data that you want to replace with == ";
       getline(cin, data3);
       file.open("Reading.txt", ios::out);
       for (int i = 0; i < temp2; i++) {
              if (data[i] == data2) {
                     data[i] = data3;
                     file << data[i] << endl;
              }
              else
                     file << data[i] << endl;
       }
       file.close();

       //printing just data
       file.open("Reading.txt", ios::in);
       temp2 = 0;
       while (file) {
              string temp;
              getline(file, temp);
              cout << temp2 + 1 << "  " << temp << endl;
              temp2++;
       }

}


Output:

C Plus Plus Program to Replace a specified Line in a Text File - cppexamples


Related Articles:


C Plus Plus Program to Create a File & Store Information

C Plus Plus Program to Illustrate Reading of Data from a File
If You Enjoyed This, Take 5 Seconds To Share It