C++ istream / ostream equivalent ?
Matthias Pleh
gonzo at web.net
Wed Dec 1 11:45:47 PST 2010
>
> 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;
}
More information about the Digitalmars-d-learn
mailing list