Link to home
Start Free TrialLog in
Avatar of win32
win32

asked on

(CString) BOOL

Hi

Is there an esy way to convert a BOOL to a string, like "1" = TRUE, "0" = FALSE

CB.
Avatar of smitty1276
smitty1276

char boolString[2];
bool boolVal = whatever;

if( boolVal == true )
  strcpy( boolString, "1" );
else
  strcpy( boolString, "2" );


unless you use .NET ( C# ) or Java, in C++ there is no such API or STD function. Why don't you define a little helper class, that contains the values and their string representations, and have methods as BooleanValue ( from CString, from char*, etc, ) and ToString (from bool). Take a look at Java's String and Boolean classes for some good examples
string boolToString(bool toConv){
  if (toConv == true){
    string tr = "True";
    return tr;
  }
    string fa = "False";
    return fa;
}

I guess this should work...
ASKER CERTIFIED SOLUTION
Avatar of nietod
nietod

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Opps did anyone notice this is for a "CString"  ie. MFC?

You could use CString's Format() member for this.  You could take advantage of the fact that when bool is cast to an int false becomes 0 and tue becomes 1, like

CString S;
bool f = false;

S.Format("this is false: %i", (int) f);


HOWEVER, variable argument procedures like Format() are a little risky to use.  I woudl avoid them wherever possible.  So I woudl actually do something more like what smitty suggested.
BOOL b;
CString str = b?"TRUE":"FALSE";

or

bool b;
std::string str = b?"TRUE":"FALSE";
Avatar of Paul Maker
>>HOWEVER, variable argument procedures like Format() are
a little risky to use

why neitod
VA functions provide no-type safety.   Simple mistakes that would ordinarly be caught by the compiler are not detected and can result in crashes or erratic behavior.
is there any safe alternative then ?
Yes.  STL doesn't use any VA functions.  In fact, the STL stream classes were developed as a way to avoid VA functions like printf()  (Long before templates were added to the langauge and long before STL was called STL).
What about something as simple as
   return (char)(false + 48); // = '0'
   return (char)(true + 48); // = '0'

#include <afx.h>

char     GetAnswer(bool blnAnswer)
{
     return ((char)(blnAnswer + 48));
}

void main(void)
{
     printf("%c\n"     , GetAnswer(true));
}



...that should have read...

  return (char)(false + 48); // = '0'
  return (char)(true + 48); // = '1'
Why assume that '0" is 48 dec?

Yoiu could do

char     GetAnswer(bool blnAnswer)
{
    return (char)((int)blnAnswer + '0');
}

But seeign as this is askign for a CString, not a char, I don't see how this is that useful.  

bool theBool = false;
CString S = theBool?'1';'0';

would be more useful.