JdBP> JdBP>> cin.getline(name, sizeof name) ; // Note: no EOF checking
JdBP> JdBP>> if (!strcmp(name, "Cyber Con")) {
JdBP> JdBP>> cout << "Hello " << name << endl ;
JdBP> JdBP>> ofstream file("file1.fil", ios::out|ios::trunc) ;
JdBP> JdBP>> file << name << endl ;
JdBP> JdBP>> }
RS> Very interesting.... you don't even have to open the file
RS> explicitly.
Since I seem to be avoiding studying for my exam anyway, I thought I'd add a
comemnt here.
In C, as with most procedural languages, you think in the domain of the
solution. That is, if your problem is saving data to disk, the solution is
to open a file, write the data, and close the file.
In C++, as with all OOPLs (AFAIK), you are to think in the domain of the
PROBLEM. That is, given the same problem, the "solution" is the problem: put
the data (object) in the file (object). The objects will know how to handle
themselves (or, rather, are to be written to be able to handle themselves).
This is the basic difference. Stop worrying about what is happening below
your layer of abstraction - ignore the "nitty gritty" details. Only worry
about the "nitty gritty" details of your own class type when you are
implementing it. This has the advantage of removing yourself from the
details of every other object type in the system, except the ones you need to
deal with, and even then, you should only have cursory knowledge of these.
The advantage? Let's say you have a class foo, with a function "bool
writeTo(ostream& os)" which takes a stream to write to (can be ofstream,
ostringstream, oMyOwnStream, or, specifically, cout or cerr). Its advantage
is right there: it can suddenly write to ANYTHING... even memory
(ostringstream)! Written properly, a readFrom(istream&) should be able to
restore your object state from the stream that writeTo() saved to... even
allowing in-memory "copying" via serialization. Imagine a stream that
"pretty-printed" everything into PostScript(tm) and directed it to... you
guessed it, another stream (to save to file or print to spooler). If your
writeTo() printed ASCII, it can now be pretty-printed (unless the
pretty-printer needs help to pretty print something).
Can't do that if your C "writeTo()" function uses FILE*'s only. You'd have
to write one to copy to FILE*'s, one to copy to POSIX's "int" handles
(open/close), one to write to growing vectors (the string stream) - one for
each type of growing vector, whether it's home-grown or some third-party
library! Yuk. And then writing one to send its data (probably all at once -
prepare your own memory buffer!) to the pretty-printer that you didn't know
about when you first wrote your function set...
The point is that objects handle themselves - you only have to handle them
when they are either poorly written, or you're writing them (so you're
writing their handling code - their class).
---
---------------
* Origin: Tanktalus' Tower BBS (1:250/102)
|