Reading unsigned values from string streams.

Discussion in 'C++' started by BigMan, Jun 11, 2005.

  1. BigMan

    BigMan Guest

    Let's consider the following piece of code:

    unsigned int ui;
    std::istringstream StrStream( "-1" );
    StrStream >> ui;

    How do I catch the case when StrStream contains negative numbers?
    BigMan, Jun 11, 2005
    #1
    1. Advertising

  2. BigMan

    Mike Wahler Guest

    "BigMan" <> wrote in message
    news:...
    > Let's consider the following piece of code:
    >
    > unsigned int ui;
    > std::istringstream StrStream( "-1" );
    > StrStream >> ui;
    >
    > How do I catch the case when StrStream contains negative numbers?


    Extract them and store them in a signed type object
    (e.g. 'int' or 'long'), and check if less than zero.
    (By definition, an unsigned object cannot represent
    negative values). Because of the language's overflow
    rules for unsigned types, (unsigned int)-1 == UINT_MAX.
    (Overflow of signed types results in 'undefined behavior'.)

    -Mike
    Mike Wahler, Jun 11, 2005
    #2
    1. Advertising

  3. BigMan

    BigMan Guest

    And how do I read values of pointer types?
    BigMan, Jun 12, 2005
    #3
  4. BigMan

    BigMan Guest

    OK, let's suppose that I first read the value into an object of type
    long. Then I'll have to make sure that this value fits in the signed
    type. Is there a standard way to achieve this? May I use
    std::numeric_limits::min and std::numeric_limits::max for this purpose?
    And, by the way, does signed/unsigned comparison yield defined behavior?
    BigMan, Jun 12, 2005
    #4
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Timo Freiberger
    Replies:
    3
    Views:
    942
    Bob Hairgrove
    Oct 30, 2004
  2. George Marsaglia

    Assigning unsigned long to unsigned long long

    George Marsaglia, Jul 8, 2003, in forum: C Programming
    Replies:
    1
    Views:
    674
    Eric Sosman
    Jul 8, 2003
  3. Replies:
    3
    Views:
    418
    James Kanze
    Nov 19, 2008
  4. Leslaw Bieniasz
    Replies:
    2
    Views:
    1,036
    Thomas J. Gritzan
    Jan 15, 2010
  5. pozz
    Replies:
    12
    Views:
    738
    Tim Rentsch
    Mar 20, 2011
Loading...

Share This Page