Write a program which asks file name from keyboard, opens a file with that name for output, reads the line from keyboard character by character and writes the line onto the file.

Sep 22, 2018

Program :

#include<iostream>
// for file operations
#include<fstream>
using namespace std;

int main(){
	char file_name[30],ch = ' ';
	cout<<"Enter file name to open:"<<endl;
	cin>>file_name;

	// now open file in output mode
	fstream myfile;
	myfile.open(file_name,ios::out);
	// now read the line characterwise and write it to a file
	cout<<"Enter the line to write to file"<<endl;
	//reads character from console
	cin.ignore();//ignore new line characters left in stream
	while(1){
		cin.get(ch);
		if(ch == '\n'){
			break;
		}
		myfile.put(ch);
	}
	myfile.close();
	return 0;
}

Sample Run:

Enter file name to open:
hello.txt
Enter the line to write to file
hello this is the line to be written to the file

 

Related


Tools/Apps





© Nepal Exchange Rates