|
|
Warp wrote:
> Actually there is a way to achieve the same thing with std::cin
> directly, without having to use stringstreams.
>
> If an input stream fails to read data which fits the parameter type,
> it will stop reading, so anything that was in the input (which was not
> whitespace) will be left there. It's thus possible to check if reading
> the integer filed, and if it did, read it as a string.
> The only catch is that you have to clear the error flags of std::cin
> before you can continue reading properly.
Thanks for the tip.
By the way... what's the usual C++ idiom for handling failure?
In Haskell, if you have some function that could fail for some reason,
you have two options:
1. Throw an exception if there's a problem. (Only I/O code can catch and
handle exceptions.)
2. Use the "maybe" datatype, which contains either some data, or a
"there's nothing here" flag. (And because the type is different, the
caller *must* explicitly check which it is before using the result for
anything.)
Typically you throw an exception for something like "we ran out of
memory" or "you called with an invalid argument". But for something
like, say, looking up a key in a dictionary, it's a very predictable
thing that the key might not actually exist, so the "maybe" approach is
used there.
What is the "usual" C++ style for this kind of thing? (I'm asking a
question of style here; clearly there are several possible things you
*could* do in C++.)
--
http://blog.orphi.me.uk/
http://www.zazzle.com/MathematicalOrchid*
Post a reply to this message
|
|