Can I use ifstream and istream both?

May 3, 2011 at 12:35pm
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?
May 3, 2011 at 1:01pm
http://www.cplusplus.com/forum/articles/40071/#msg225674

...to paraphrase a famous sports ad: Just Try It! :D
May 3, 2011 at 1:08pm
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.
May 3, 2011 at 1:17pm
@ 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?!?
May 3, 2011 at 2:39pm
If you are going to use an fstream you have to previously connect the file to the stream using stream_name.open();
May 3, 2011 at 3:27pm
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 May 3, 2011 at 3:28pm
May 5, 2011 at 4:03pm
Can you please explain more or show me your code so that I can tell you where the mistake is?
May 9, 2011 at 7:43am
I already fixed it, thanks anyway !
May 18, 2011 at 12:39pm
@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.