Please click on 1-2 Ads to keep this website's Study Material FREE and regularly Updated.

Program 37: Write a C++ program to replace a particular line in a file with the string given by user.

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

int main()
{
	fstream f ,fin;
	char str1[50],str[50];
	int n;
	f.open("C:\\Users\\Sandeep\\Desktop\\file1.txt",ios::in|ios::app);
	fin.open("C:\\Users\\Sandeep\\Desktop\\file2.txt",ios::in|ios::app);
	cout<<"\nenter the line number u want to replace : ";
	cin>>n;
	cin.ignore();
	cout<<"\nenter the new string : ";
	gets(str1);

	if(!f)
		cout<<"\nfile doesnt exist ";
	else
	{
		int i=1;
		while(f)	
		{ 
			f.getline(str,50,'.');
			if(i==n)
			fin<<str1;
			else
			fin<<str;
			i++;
		}
		cout<<"\nline replaced successfully!!";
	}	

	f.close();
	fin.close();
	return 0;
}



If you have any suggestion or found any error in the above program, then do let us know at [email protected] or just comment below.