You are here:

C++/C++ Object

Advertisement


Question
Hi Vijayan,
In below program,
how if condition ( a.data() != "") has succeeded..

if i try ( a != ""), condtion failed.
Kindly explain, What is logic behind that and which one is correct usage?

int main()
{
  string a;
  string temp;

  if(a.data() != "" )
  {          
       temp = "From:";
        temp +=  a.data();
        temp += "\n";
   }
 cout<<"Temp "<<temp.data()<<std::endl;
}

Answer
The function data() returns a pointer (const char*) to the first character in the buffer maintained by the string. In general, do not use it except for low level programming using direct buffer access.

So, a.data() != "" just compares the two pointers, and is certainly not what you want to do in this case. To compare two strings, use the strings directly. a != "" is the correct way to check if the string is not empty. You could also use the empty() function to check if the string has no elements; this is the preferred way.

if( !a.empty() )
{
    // string a is not empty. process it
    // ...
}

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++09. i would not answer questions about gui and web programming.

Experience

over 15 years

Education/Credentials
post graduate engineer

©2012 About.com, a part of The New York Times Company. All rights reserved.