# boost::lexical_castbool

## Recommended Posts

I'm having a little bit of trouble with boost::lexical_cast<bool> and and c-style strings.
char* s = "true";

if( boost::lexical_cast<bool>(s) )
printf("\n True!! \n");
else
printf("\n False!! \n");

Even with something this simple, I keep getting the boost::bad_lexical_cast exception thrown.
Quote:
 From http://lists.boost.org/Archives/boost/2002/05/30088.php If we allow implicit conversion (the seconds step), then a careful study of the conversion rules in C++ is needed, to make sure it does the right thing. For example, there's an implicit conversion from a pointer, to bool, so "bool b=lexical_cast("false")" (when boolalpha is enabled) will always give true (because the char * pointer is non-null). This needs to be checked for, and handled, at the "special case" step. That's why that step has to be first.
Although this isn't exactly my problem, since I'm using a char* string and attempting to convert to bool, I was wondering if this could be the problem. Could it be that because I'm attempting to convert to a boolean, and that it's a char pointer?

##### Share on other sites
You're looking at a discussion. Not documentation that describes how it actually acts.

##### Share on other sites
I realise that, but I'm grapsing at straws. I'm using lexical_cast for booleans the same way that I'm using it for doubles, floats and integers, and it's not working. It only throws an exception for the boolean cast, and I haven't yet been able to find something in the boost documentation that might hint at what the problem is.

##### Share on other sites
Is there a specific reason you need to cast a char* to a boolean? Why not simply strcmp() them, it'll prevent needing an additional library, it's a standard function, and it's very simple.

char* s = "true";if(strcmp(s,"true") == 0)    printf("\n True!! \n");else    printf("\n False!! \n");

##### Share on other sites
I definately could, but since I'm using boost for everything else in that area of my engine, I was wondering if there was a quick and easy fix to get it working.

I could use strcmp, but when using boost::lexical_cast to convert to a boolean, does is it case sensetive? Because I'd have to do a tiny bit of fiddling if I used strcmp.

##### Share on other sites
Where are you getting the strings "true" and "false" from? I think you'd have better luck converting from "0" and "1"

##### Share on other sites
Quote:
 Original post by RDragon1Where are you getting the strings "true" and "false" from? I think you'd have better luck converting from "0" and "1"

std::boolalpha enables input and output of boolean values in text form. The exact strings being used depend on the stream's imbued locale.

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
627719
• Total Posts
2978789

• 9
• 21
• 14
• 12
• 42