ofstream is not creating a file

Hello c++'ers,

This is hopefully quite a simple problem but it is driving me a bit nutty! Here is the code in question:

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
32
33
34
35
36
37
	bool new_database=true;
        int dbno(1);
	ostringstream title;
	string sTitle;
	title << "data" << dbno << ".database" << endl;
	sTitle=title.str();
	

	fstream test(sTitle.c_str());
	if(!test.is_open())
		{new_database=true;}
	else
		{new_database=false;}
	test.close();

        ofstream out((title.str()).c_str());
	if(out.is_open()){cout << "File is open" << endl;}
	if(new_database==true)
	{
		out << "#" << endl;
		out << subject << endl;
		out << "#" << endl;
	}

	out << "#" << endl;
	out << id << endl;
	for(int i=0;i<years;++i)
	{
		out << "Year " << i+1 << endl;
		for(int j=0;j<(int)courses[i].size();++j)
		{
			out << courses[i][j].first << " "<< courses[i][i].second << "%" << endl;
		}
	}

	title.str("");
	out.close();


Essentially all I want to happen is the program checks if data1.database exists by trying to open it with the fstream and then creates it using the ofstream. However the program isn't creating the .database file even though I've passed a character array to the ofstream parameter list.

Please help, where am I going wrong! :(
closed account (zb0S216C)
As far as I can tell, you never assign a string to title. So when you pass title in the constructor of out, it fails to open the file as title isn't holding a string.

Edit: ------------------------------------8<-----------------------

sTitle equals an empty string on line 6. In test's constructor, you attempt to open a file with an empty string.
Last edited on
I have made title a string using the .str() command, however it doesn't even work if I pass title.str() to sTitle first. e.g.

string sTitle=title.str();
ofstream out(sTitle.c_str())

also doesn't work, however according to the debugger title and sTitle are holding data1.database.

Interestingly ofstream out("data1.database") works.
Sorry everyone I've seen the problem and I'm an idiot.

Line 5 I've included an endline character which is messing everything up. lol this thread may be deleted.
closed account (zb0S216C)
If you've made changes to your code, it would be helpful if you update it.

however it doesn't even work if I pass title.str() to sTitle first.

That's because title was never assigned a character sequence. Then, on line 6, sTitle takes the character sequence of title. However, at this point, title isn't holding a character sequence and therefore, sTitle equals nothing.

On line 9, you attempt to open a file with sTitle, which is holding nothing.
Last edited on
Topic archived. No new replies allowed.