1

I am new to using boost::lexical_cast and have minimal understanding of its internals. I am trying to do the following cast:

string someString = boost::lexical_cast<char>(sourceString);

However, boost is complaining that the above code is:

[Exception]: bad lexical cast: source type value could not be interpreted as target

The source is a string, however it will always only be 1 character long.

Could someone please explain?

Thanks.

czchlong
  • 2,434
  • 10
  • 51
  • 65
  • 1
    Was there a reason you're doing that instead of something like `char c = *(sourceString.c_str());`? And why are you turning a string into a char and putting it back into a string? – Seth Carnegie Oct 28 '11 at 14:26
  • 3
    Or perhaps `char c = sourceString[0];`? – Mike Seymour Oct 28 '11 at 14:26
  • @MikeSeymour or you could just do that... – Seth Carnegie Oct 28 '11 at 14:28
  • @set - sorry i didn't write that part properly, i meant to declare it as a char. i could do that, but i would just like to understand why boost cannot convert it properly. thanks – czchlong Oct 28 '11 at 14:31
  • 2
    Also, this won't compile, since you can't convert the `char` result of `lexical_cast` to a string. Once I fix that, the code [works](http://ideone.com/BkGOy) as long as `sourceString` contains a single character. – Mike Seymour Oct 28 '11 at 14:32
  • What @Mike said; `string` doesn't have a constructor taking a `char`. You could probably do `string someString(boost::lexical_cast(sourceString), 1);` and make it work, but that is the _really long way around_. You're far better off doing `char str = otherstr[0]`. – Seth Carnegie Oct 28 '11 at 14:33

1 Answers1

4

When I test it (after fixing the invalid conversion from char to string), the lexical cast succeeds as long as sourceString contains a single character. Here are the test results.

If your real code doesn't work, then please post more of it; preferably a runnable program that demonstrates the error.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • thanks for the answer. I have a vector and I know that string at position index x would only be one character, so essentially I am doing the following: char someChar = lexical_cast(tokens[x]); this is what is throwing the error. Sorry, should have posted that before. Thanks. – czchlong Oct 28 '11 at 15:11
  • 2
    Perhaps you should check your assumptions; add `assert(tokens[x].length() == 1);` before the cast to make sure that what you know is actually what is happening. – Mike Seymour Oct 28 '11 at 15:14
  • yes Mike you are correct, my assumption was incorrect. Thanks! – czchlong Oct 28 '11 at 15:16