C++ istream / ostream equivalent ?

vincent picaud vincent.picaud at laposte.net
Thu Dec 2 05:48:12 PST 2010


Pelle Månsson Wrote:

> On 12/02/2010 09:05 AM, vincent picaud wrote:
> > 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
> >
> >
> 
> What you want is the new writeTo system for output. For input, a 
> readFrom would be symmetrical and make sense :-)
> 
> To actually use it, you would just do myFile.write(your, stuff, etc);
> 
> For now, you can stringify using toString(). No way to read yet, except 
> to!int, etc.
> 

Yes, that is exactly what I want :)
Thanks



More information about the Digitalmars-d-learn mailing list