C++ istream / ostream equivalent ?
vincent picaud
vincent.picaud at laposte.net
Thu Dec 2 00:05:06 PST 2010
Matthias Pleh Wrote:
>
> >
> > Thank you for your reply and yes that works :)
> >
> > Now i m facing with the following problem, what is the trick for input stream ?
> >
> > ( something like
> >
> > std::istream& operator>>(std::istream& in,A& a)
> > {
> > // A.someData<< in;
> > return in;
> > }
> >
> > in C++ )
> >
> > I m thinking of the situation when we want to load some data from a file.
> >
> > The toString() trick is okay for saving the object... but how to load it back (something like fromString(char[]) would do the job but it does not exist in Object) ?
> >
> > Anyway thank you, you solved half of my problem :)
> >
> >
>
> Ther are many posibilities, depending on your further needs! Just have a
> look at the online dokumentation:
> http://www.digitalmars.com/d/2.0/phobos/phobos.html
>
> But my first try would be such ..
> (note: I've leaved out error-handling ...)
>
> module test;
>
> import std.stdio;
> import std.file;
>
> class A
> {
> void writeToFile() { std.file.write("sample.txt",someData); }
> void readFromFile() { someData=cast(string)read("sample.txt"); }
> void clear() { someData="n/A\n"; }
> string toString() { return someData; }
> private:
> string someData="Just some data.
> With anohter line of date.
> Even more data.!";
> }
>
> int main(string[] args)
> {
> A a=new A;
> a.writeToFile();
> a.clear();
> writeln(a);
> a.readFromFile();
> writeln(a);
> return 0;
> }
thank you for all your answers. I understand the approach, but in the same time, I have the feeling that the C++ way is more convenient.
Look in C++ , to define I/O for A, you do not have to modify your class A and simply have to overload two functions:
std::ostream& operator<<(std::ostream& out,const A& a)
std::istream& operator>>(std::istream& in,A& a)
moreover this smoothly extend the I/O C++ framework without other side effect.
I was expecting to find a similar mecanism in D/Phobos
Perhaps by overloading some read(), write() functions of the Phobos library, but I do not know if it is "moral" to do that and which phobos functions are concerned... IMHO there is a documentation hole here
More information about the Digitalmars-d-learn
mailing list