Writing a file using ofstream

Here is my code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//Using ofstream to write to a file

#include<fstream>
#include<iostream>
#include<string>

int main(){
	using namespace std ;
	//Getting filename
	cout <<"Enter the name of the file ";
	string filename ;
	cin >> filename ; 
	
	//creating the file
	ofstream outf(filename); //error 
	if(!outf){
		cerr << "File could not be created " << endl;
	}
	
	//Getting filedata
	cout << "Enter the data to be written to the file";
        char data[100]
	cin.getline(data,100);//only writes the first word of line
	
	
	//Writing data to the file
	outf << "This is the start of the file " << endl;
	outf << data << endl ;
	outf << "This is the end of the file " << endl;
	return 0;
}


If the change the filename to char * filename , it gives runtime error ie the program simply crashes.

did you initialize the pointer char* filename ?

example:
1
2
char*filename; 
filename = new char[10] //initialize the pointer 



I tried the code using char* filename and it runs ok :)
Last edited on
Simpler example:
char filename[10];
Well , I tried doing it like this and the program crashed in between.
1
2
char *filename ;
cin >> filename ;


I changed the code to
1
2
char *fname = new char[30];
cin.getline(fname,30);


and now , it works fine.. thanks
Topic archived. No new replies allowed.