Reading unsigned values from string streams.

B

BigMan

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?
 
M

Mike Wahler

BigMan said:
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
 
B

BigMan

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?
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top