problem in opening file in c++

please can someone tell where i am making the mistake,, I simply can't open the file "INTEGET.TXT" by switch case.

code:

#include<iostream>
using namespace std;
#include<fstream>
int main()
{
int x,y,z,xd;
cout<<"\n 1.Write ";
cout<<"\n 2.Read ";
cout<<"\n Enter Choice ";
cin>>xd;
switch(xd)
{
case 1: ofstream ofile;
ofile.open("INTEGER.TXT",ios::out);
cout<<"\n Enter Three Integers ";
cin>>x>>y>>z;
ofile<<x<<y<<z;
ofile.close();
case 2: ifstream ifile;
ifile.open("INTEGER.TXT",ios::in);
cout<<"\n Three Integers are : ";
ifile>>x>>y>>z;
cout<<x<<y<<z;
ifile.close();
}
return 0;
}
Does the file exist? Is it in the directory your implementation expects to find files at run time (usually the main project directory)?

Note: case 1 has no break statement and will fall through to case 2.

PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.
The code won't compile for me. The reason is that a variable (ofile) is declared inside the switch statement, and will be visible during the whole of that block. However, if case 2 is executed, the variable ofile will not be properly initialised.

This is a rather technical point which may be difficult to understand. For now, the main point is to enclose the code for each case in its own braces { } which will limit the scope of the variable names to only that part where they are needed.

Your code is also missing a break; statement at the end of each case.

Something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
    switch(xd)
    {
        case 1: 
        {
            // code for case 1 goes here
        }
        break;
                
        case 2:
        {
            // code for case 2 goes here
        }
        break;
    }
Last edited on
Topic archived. No new replies allowed.