In my program I have function Get_auto()
;
I want it to do something like this:
void Cook::Get_auto(){
ifstream ifile;
ifile.open("sourcek.txt");
char choice;
ifile >> choice;
switch (choice)
{
case '0': lvl = 0;
break;
case '1': lvl = 1;
break;
case '2': lvl = 2;
break;
case '3': lvl = 3;
break;
case '4': lvl = 4;
break;
}
}
The problem is that I want to use the Get_auto function multiple times, each time loading the data below the last used part of a file. How should I do this?
Move the ifstream to the class as its private field. Then, create a method Cook::open
, where you open the ifstream. In Cook::Get_auto
only use the >>
operator. Call the open
method before you call the Get_auto
method for the first time.
Something like this: (assuming its a C++ code, this will be in the header file)
private:
ifstream ifile;
public:
void open();
void Get_auto();
and this will be in the source file:
void Cook::open() {
ifile.open("sourcek.txt");
}
void Cook::Get_auto(){
char choice;
ifile >> choice;
switch (choice)
{
case '0': lvl = 0;
break;
case '1': lvl = 1;
break;
case '2': lvl = 2;
break;
case '3': lvl = 3;
break;
case '4': lvl = 4;
break;
}
}
It would be wise also to add some checking whether ifile
is open and whether you can read from it.