I was going through legacy code to fix a problem and found out that checking c_str in the following manner does not work. However if I change the comparison to string.empty() it works. So my problem is solved, but I am not sure why the c_str comparison does not work.Any idea why?
Thanks!
I am using - gcc version 4.1.2 20080704 (Red Hat 4.1.2-46).  
#include <iostream>  
using namespace std;  
int main()
{
   string a="";
   if (a.c_str() == NULL)
   {
     cout <<"char says empty"<<endl;
   }
   if (a.empty())
  {
    cout << "string says empty"<<endl;
  } 
 }
The output is-
        string says I am empty  
a is not null in this case.  The string object has an internal pointer, which is not null, and that pointer is what c_str returns.
To verify this, try
printf("%zu\n", a.c_str());
and you will get a real address.
A null terminated string is never NULL, it always points to valid memory with a null terminator. The empty string is just a single \0. Since c_str() is contracted to return a null terminated string it can never return NULL. The correct way to test for an empty string is indeed empty().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With