Switch statement and Writing to a file

I have a ofstream within a case.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
  case 1:
	ofstream myfile1 (file18.c_str(), ios::app);
	if (myfile1.is_open())
	{
	while (myfile1.good())
	{
	myfile1 << choice1;
	myfile1.close();
	}
	}
	else 
	{
	cout << "Unable to open file"; 
	}

I get this error:
c:\documents and settings\owner\desktop\xx\xx\xx.cpp(497) : error C2360: initialization of 'myfile1' is skipped by 'case' label

Why does the write file not work within a case? How do I fix what I already have? And is there a better alternative to the code that I have?
You can't create automatic objects in the middle of a switch statement just like that.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//Bad:
switch (x){
    //...
    case n:
        //...
        T object;
    //...
}

//Good:
switch (x){
    //...
    case n:
        {
            //...
            T object;
            //...
        }
    //...
}
I reckon this has something to do with switch being a sequence of unstructured gotos. If you try creating an object between a forward goto and its label, you'll get the same error.
Posting the rest of your program would be beneficial. Maybe try to declare the myfile outside of the case statement?
Topic archived. No new replies allowed.