Classic: String to Boolean..;=(

I parse a SMS (String) to substrings, so i can't avoid Strings.
The (sub)String is called StringFoo and is "1".
I want to write that 1 into a struct. The scruct contains chars[] and booleans, like

typedef struct {
  boolean booleanBar;
  char charBar[20];
} userstruct;
userstruct owner;

StringFoo.toCharArray(owner.charBar, 20);

works perfect.

I search for an elegant way for the boolean, something like:

StringFoo.toBool(owner.booleanBar, 1);

Do i have to build a (if then) thing ? Do i just don't see the obvious? It' kind of ugly anyway...

Thx for hints!

That may be true, but possibly not

Please post a complete sketch rather than just an isolated snippet so that we can see what you are doing in context

if you get 0 when you want false and 1 (or any other number) when true, then Try

owner.booleanBar = StringFoo.toInt();

C++ has a rule that implicitly converts 0 into false and any other integer into true.


owner.booleanBar = StringFoo != "0";

this offers better type coherence so I like the idea, but it's costly.

Same idea but cheaper

owner.booleanBar = *(StringFoo.c_str()) != '0';

Why not StringFoo[0]

yes that works too or charAt(0) . (but more costly because of the bound check )

That's it!! Thx a bunch!

that's costly too in terms of compute time.

the fastest is probably

owner.booleanBar = *(StringFoo.c_str()) != '0';

that means "take the first character from the string and compare it to '0')

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.