Comparing to a hardcoded string with quotes in C++

tasteslikelemons picture tasteslikelemons · Mar 12, 2014 · Viewed 21k times · Source

I'm writing a c++ function to generate XML using TinyXML. I'd like to verify that a (relatively small) tree produced by my function gets turned into a string identical to a reference string.

// intended XML:
<element type="correct" />

It seems like the easiest way to do this comparison is to hardcode the reference string into the code:

//assignment
std::string intended = "<element type=\"correct\" />";

However, the backslashes to escape the quotes prevent the comparison from succeeding.

#include <tinyxml.h>
#include <string.h>
TiXmlElement test = TiXmlElement("element");
test.SetAttribute("type", "correct");
TiXmlPrinter printer;
test.Accept(&printer);
ASSERT_EQ(intended, printer.CStr()); // gtests macro

output:

Value of: printer.CStr()
Actual: "<element type="correct" />"
Expected: intended
Which is: "<element type=\"correct\" />"

Answer

wimh picture wimh · Mar 12, 2014

On the googletest Primer page I read that ASSERT_EQ() compares pointers. (which are only equal if they point to the same memory location). If you want to compare strings, you should use ASSERT_STREQ().

ASSERT_STREQ(intended, printer.CStr());