-7

Here is my code:

const TiXmlAttribute* pAttr = pElem->FirstAttribute();
const char* name = pAttr->Name(); // attribute name
const char* value = pAttr->Value(); // attribute value
float _D = 0.0;

if("SRAD" == name)  // returns false here, but name is indeed "SRAD"
{
    _D = atof(value);
}

The problem is the name is "SRAD", but the if condition returns false. Anyone educate me why? Thanks.

Ono
  • 1,357
  • 3
  • 16
  • 38

3 Answers3

4

This compares the pointers, not the contents.

You need to use strcmp:

if(strcmp("SRAD", name) == 0)
Mike DeSimone
  • 41,631
  • 10
  • 72
  • 96
3

You're comparing pointer values, not string contents. The pointers will (almost certainly) not be equal, even if the strings are.

Either use std::string, for which == and other operators compare the string contents:

#include <string>

std::string name = pAttr->Name();
if("SRAD" == name) // works as expected

or delve into the C library

#include <cstring>

if (std::strcmp(name, "SRAD") == 0)
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
1

If you even write the following way

if ( "A" == "A" ) { /* do something */ }

the result of the condition can be either true or false. The problem is that in this condition string literals that have types of array char[2] are converted to pointers to their first elements. And the compiler may store equal string literals either in diferrent extents of memory or store only one representation of the same string literals.

Thus in this statement

if("SRAD" == name)

you are comparing addresses of the first elements of string literal "SRAD" and of the array pointed to by pointer name.

You should use standard C function strcmp declared in header <string.h>. For example

if( strcmp( "SRAD", name ) == 0 ) /* ...*/;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335