Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing to a hardcoded string with quotes in C++

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\" />"
like image 615
tasteslikelemons Avatar asked Mar 12 '14 21:03

tasteslikelemons


People also ask

How do you compare strings with quotes?

equals() Method. You can also use the Objects. equals() method in Java to compare two strings either initialized with a new keyword or directly using double-quotes. This method checks whether both the strings objects are equal and if so, return true.

Can I use == to compare strings in C?

You can't compare strings in C with ==, because the C compiler does not really have a clue about strings beyond a string-literal.

Can you compare a string with a character in C?

String comparison in C also possible by using pointers. In this approach, we use pointers to traverse the strings and then compare the characters pointed by the pointer. Explanation: In the code example, We've declared two char arrays str1 ,str2 and then take input for them.

How do you compare string elements with characters?

strcmp() in C/C++ It compares strings lexicographically which means it compares both the strings character by character. It starts comparing the very first character of strings until the characters of both strings are equal or NULL character is found.


1 Answers

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 C strings, you should use ASSERT_STREQ().

ASSERT_STREQ(intended, printer.CStr());

If you want to compare std::string objects, you can do it this way1:

ASSERT_EQ(intended, printer.Str());

1 Contributed by johnfo through a comment.

like image 122
wimh Avatar answered Oct 02 '22 18:10

wimh