POV-Ray : Newsgroups : povray.off-topic : My first C++ program : Re: My first C++ program Server Time
30 Sep 2024 19:28:41 EDT (-0400)
  Re: My first C++ program  
From: Warp
Date: 19 Sep 2008 11:31:55
Message: <48d3c5ea@news.povray.org>
Invisible <voi### [at] devnull> wrote:
> ...you mean, you can take a string and make a stream that will read from 
> it? (Or, presumably, write to it, if you desire.)

  Correct. Or, more precisely, you can write to an ostringstream and then
get a regular string out of it (with the str() function).

  Where this becomes fancy is when a function takes an std::istream or an
std::ostream reference, for example:

void readSomethingFrom(std::istream& is) { ... }
void writeSomethingTo(std::ostream& os) { ... }

  You can give those functions any of these things:

readSomethingFrom(std::cin);

std::ifstream inputFile("filename.txt");
readSomethingFrom(inputFile);

std::istringstream iss(someString);
readSomethingFrom(iss);

writeSomethingTo(std::cout);
writeSomethingto(std::cerr);

std::ofstream outputFile("filename.txt");
writeSomethingTo(outputFile);

std::ostringstream oss;
writeSomethingTo(oss);

  The functions themselves don't know (and don't need to know) what the
exact type of stream actually is. All of them are used in the same way.
For example:

void writeSomethingTo(std::ostream& os)
{
    for(int i = 0; i < 10; ++i)
        os << i << "\n";
}

  This is, in fact, pure object-oriented programming (all of those things
are inherited from std::istream or std::ostream, so they can be given to
those two functions). Beautiful.

> So what exactly do the good() and fail() functions do?

http://www.cplusplus.com/reference/iostream/ios/good.html
http://www.cplusplus.com/reference/iostream/ios/fail.html

  Basically you can think of good() as "did the last read succeed?"
(the most common reason for the stream to be not good() is EOF).
It's an overall "is the stream still good?".

  And fail() as "did the input contain a value of the correct type?".
In other words, with the "std::cin >> integer; if(std::cin.fail() ..."
you are asking "did reading an integer fail?". The most common reason
for fail() to be true is that input did not contain what was expected
by the parameter (in this example an integer value).

-- 
                                                          - Warp


Post a reply to this message

Copyright 2003-2023 Persistence of Vision Raytracer Pty. Ltd.