Boost logo

Boost :

From: Vladimir Prus (ghost_at_[hidden])
Date: 2003-04-21 00:56:03


Kevlin Henney wrote:

>> int main()
>> {
>> boost::lexical_cast<int>(std::string(" 0"));
>> }
>>
>>Note the space in string. The exception does not occur with gcc 2.95, but
>>only with 3.2. I wonder if this should/can be fixed? Personally, I'd
>>expect this code to work.
>
> This is a gcc 2.95, errm, 'feature' :->

Ok.

> The code should not work, and
> the behaviour with 3.2 is correct. It all depends on your expectation,
> but according to the principle of least astonishment lexical_cast<int>("
> 0") should have the same success as lexical_cast<int>("0 "), which
> fails. If you want leading and trailing whitespace to be removed, remove
> them.

The principle of least astonishment can be applied in a different way. We
all know that lexical cast uses streams, and

    stringstream ss(" 1 ");
    int i;
    ss >> i;
    cout << i << "\n";

certainly works. It's surprising that lexical_cast<int>(" 1 ") does not
work.

BTW, I cannot find the test case for trailing space in
lexical_case_test.cpp, and... the following works with gcc 3.2:

   int main()
   {
      std::cout << boost::lexical_cast<int>(std::string("0 ")) << "\n";
   }

Hmm ;-)

>>Is it
>>possible to output the stringstream content (if source -> stringstream
>>conversion was successfull?)
>
> This is something that I toyed with a long time ago, but eventually
> decided not to put in for a couple of reasons. One is the issue that the
> exception would hold a dynamically allocated string of potentially
> unbounded length, rather than just a short descriptive string.
> I was
> also concerned that the role of such an exception was more as a
> debugging tool than an exception handling medium.

Alas, it's not very helpfull as a debugging tool as it is. To find out
what's wrong I had:
1. Figure out what command line option causes my program to fail
2. Guess the problematic place and add try block there, just to output
the text of string that could not be converted.

Terje Sletteb? wrote:

> "Houston, we have a problem..."
>
> Hm, just now, I sent a reply to a similar problem report at Boost-Users
> list, about why whitespace skipping is turned off in the new lexical_cast
> version. It was to avoid having things like "lexical_cast<std::string>('
> '); // Space character" work, which used to throw an exception.
>
> However, it seems this change has had undesired side-effects, in that code
> like the above now fails to work.
>
> Frankly, I don't know what to do with this...

On Boost-users ml you mention two cases:

    lexical_cast<std::string>(' ');
    lexical_cast<char>(" ");

Seems like it's needed to special-case conversion to character types, just
like it's done for strings.

- Volodya


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk