Opened 10 years ago

Closed 10 years ago

#8124 closed Bugs (invalid)

No more exception when casting from negative number string to unsigned

Reported by: Bernd Raum <braum@…> Owned by: Antony Polukhin
Milestone: To Be Determined Component: lexical_cast
Version: Boost 1.51.0 Severity: Problem
Keywords: lexical_cast unsigned Cc:

Description

With gcc 4.2.4, a lexical_cast from negative number strings to an unsigned causes a bad_lexical_cast exception. With gcc 4.7.1 and 4.7.2, the value interpreted as positive integer is assigned instead. This bug occurs with Boost 1.33 and 1.51 on Open Suse and Solaris 10.

Attachments (1)

test_lc.cpp (360 bytes ) - added by Bernd Raum <braum@…> 10 years ago.

Download all attachments as: .zip

Change History (2)

by Bernd Raum <braum@…>, 10 years ago

Attachment: test_lc.cpp added

comment:1 by Antony Polukhin, 10 years ago

Resolution: invalid
Status: newclosed

I'm afraid that this is not an error.

boost::lexical_cast has the behavior of std::stringstream, which uses num_get functions of std::locale to convert numbers. If we look at the Programming languages — C++, we'll see, that num_get uses the rules of scanf for conversions. And in the C99 standard for unsigned input value minus sign is optional, so if a negative number is read, no errors will arise and the result will be the two's complement.

I do not like such behaviour, but nothing can be done.

Some code to demonstrate that lexical_cast works exactly like std::stringstream

#include <boost/lexical_cast.hpp>
#include <sstream>
#include <assert.h>

int main() {
    std::stringstream ss("-1");
    unsigned int i;
    ss >> i;
    assert(boost::lexical_cast<unsigned int>("-1") == i);
}
Note: See TracTickets for help on using tickets.