Fist time working with input in c++.
I'm trying to emulate something I do in java when I need to set a file in one place and read from it in a few others.
What I would do is make scanner (file input) a static variable and call it wherever I needed it.
This is my current code:
.h
1 2 3 4 5 6 7 8 9 10 11
usingnamespace std;
class Train;
class ifstream;
class Station {
public:
staticvoid addArivalFromFile();
staticvoid runSim();
private:
static ifstream* myfile;
};
void Station::runSim()
{
myfile = new ifstream("test.txt" , ifstream::in) ; //memory leak
test = new Train(1,3); //there are better ways, like Train test;
I don't really get what you want, as you are closing the file. ¿why don't just read all what you need the first time?
Also, keep in mind that you could make several 'Station' objects, ¿are you sure that all of them should look at the same file?
If you just want serialization then Station::serialization(istream &) will do fine. You could overlod the insertion operator '<<' too.
@JLBorges
Thanks that pointed me in the right direction.
There was one hang up. I was getting an error when I hit the linker and I just blindly wrote the line ifstream Station::myfile;
I don't know what it is but it works. I'd guess its because I never created an object for myfile. It's going to take a bit to get in the swing of c++.
Thanks again
@ne555
The Station class is entirely static.
The reason I need to be able to pull input from another method is because I'm running a long simulation and populating the timeline with an entire file from the start would be too much for the hardware i'm using. So instead I only pull more input when I need it.
You did right. A static member variable of a class in C++ is semantically equivalent to the same in Java. However, C++ makes a distinction between declaring something and defining it. myfile is just declared to be a static member variable in the class; ifstream Station::myfile; defines it.
Incidentally, do not put the definition in the header file; place it in an implementation file (ideally in Station.cxx). C++ also has an ODR - http://en.wikipedia.org/wiki/One_Definition_Rule - and a header may be included in multiple translation units.