How To Convert a Number To std::string

August 29, 2008

There are many methods available. You can use itoa, ltoa etc. to convert numbers to char*. However the following method using stringstream can convert any type of number to std::string.


#include 
using namespace std;
int main()
{
   int No = 140;  // Or you can use float No = 10.5f
   stringstream StrStream;
   StrStream << No;
   string MyString = StrStream.str();
   return 0;
}
[/sourcecode]

 
  The resulting MyString contains the value of No as string.  

Click to see how to convert string to number

Click to see how to convert CString to std::string


Slicing of Objects in a C++ Vector

August 28, 2008

Have you ever tried inserting derived class objects (not pointers to objects) to a vector of base class objects? Then what happens is the derived class objects are sliced to base class objects. See the following example.

class CBase
{
public:
   int m_BaseVariable;
};

class CDerived : public CBase
{
public:
   int m_DerivedVariable;
};

int main()
{
   vector<CBase> BaseVector;
   CDerived MyDerived;
   BaseVector.push_back(MyDerived);
   .............
   return 0;
}

Now if you watch BaseVector in a debug window, you can see that it does not have the variable m_DerivedVariable. It has been sliced to the base class object.

Of course, the same slicing will happen if you make an assignment

CBase MyBase = MyDerived;

However, things will be complicated and more error prone in a vector where you can push both base type objects and derived type objects.

Be aware of the above pitfall. At least the compiler (VC++ 6.0, I’m not sure about others) is not giving any error or warning.


Why I Prefer ‘\n’ To std::endl

August 27, 2008

Both serve the same purpose, putting a new line. The only difference is that endl causes flushing of the output buffer everytime it is called where as ‘\n’ does not.

So, if you are writing al the alphabets of English to a file using the following code,

#include ;
#include ;
using namespace std;
int main()
{
ofstream MyFileStream(“Alphabets.txt”, ios:: out);
   for (char Index = ‘A’; Index <= 'Z'; ++Index)    {       MyFileStream << Index << endl;    }    return 0; } [/sourcecode] the output buffer will be flushed 26 times while the same code with ‘\n’ instead of endl will cause it to be flushed only once and that is when the program exits (assuming that the output buffer is larger than 26 bytes).

Some Background Info

  1. Anything to be output is first queued into an output buffer and written to the device (hard disk, monitor etc…) when the queue is full. Of course, this is to ensure speed of execution as the access to the external device is less frequent.
  2. If you are in a situation where you have to avoid buffering, you can use std::endl instead of ‘\n’. An example of the above situation is when you are using old style debugging using multiple cout statements between code lines  to see where exactly a crash occurs.

BOOL to bool – Performance Warning

August 27, 2008

Once I was trying to pass a BOOL variable to a function which expected a bool value instead and I ended up with a performance warning.

warning C4800: ‘int’ : forcing value to bool ‘true’ or ‘false’ (performance warning)

It is very easy to avoid this. Put double negation in front of the BOOL variable.

#include <wtypes.h>
void MyFunc1(bool Mybool)
{
   Mybool ? cout << "True\n" : cout << "False\n";
}
int main()
{
   BOOL MyBOOL = TRUE;
   MyFunc1(!! MyBOOL);
   return 0;
}

Some Additional Information

  • BOOL is microsoft specific and type def as int . TRUE and FALSE are two macros evaluated to 1 and 0 respectively.
  • The size of BOOL is same as that of int (4 in 32 bit platforms) where as the size of bool is 1.
  • The return value of a function returning BOOL can be other than TRUE or FALSE. For example, the following function is perfectly legal.
      BOOL MyFunc(int Number)
      {
         return Number;
      }
      So it is better to avoid checking if (TRUE == MyFunc(10))
      as the return value of MyFunc(10)is never TRUE.
      Instead you can check like
      if (MyFunc(10))