Can I use ifstream and istream both?

I have a constructor Kruskal(const unsigned& , istream &is = cin ) to accept integer from standard input to construct the Kruskal object. Because ifstream is derived from istream, can use an ifstream object to read files?
http://www.cplusplus.com/forum/articles/40071/#msg225674

...to paraphrase a famous sports ad: Just Try It! :D
Hi akilguo,

yes, you can reference an istream object, such as the default input stream cin, or a ifstream object initialised to point to a data file, they will work just the same.

However, if I were you, for expandability, I would make Kruskal::Kruskal call a read(std::istream&) member function, which you can then define to read in whatever you like rather than just an int. Then you can add new data members to your class and have the option of initializing them from a data file using Kruskal::read(std::istream&) without having to change your interface.
@ matsom
...to paraphrase a famous sports ad: Just Try It! :D

I agree, you cant be afraid to try these things out,. Whats the worst that can happen?!?
If you are going to use an fstream you have to previously connect the file to the stream using stream_name.open();
Thanks, matsom and dangrr888.
Yeah, i tried, I works fine!
I know, though, " 1 item per post ", but i find a tiny problem:
When i use an ifstream object to read a file, why can't it read into the last integer if the integer is the last word of the file without any character appending , no blank space , no newline, no anything?
Last edited on
Can you please explain more or show me your code so that I can tell you where the mistake is?
I already fixed it, thanks anyway !
@Mohamed Fouad
If you are going to use an fstream you have to previously connect the file to the stream using stream_name.open();
ico

You can just do this upon initialisation:

ifstream data_file("path/to/my/data_file.txt");

then pass data_file by reference as the argument to Kruskal::read(std::istream&)].
Topic archived. No new replies allowed.