I am trying to do the following in C++, the C# code is here

test is a string btw.

if (test == null || !test.Equals("Item Name\t"))
                    return data;

I did this in C++, but its crashing the program

if (test.compare(NULL) == 0 || test.compare("Item Name\t") != 0)
            return data;

Recommended Answers

All 4 Replies

If test is a std::string, then you don't need the first comparison with NULL. This comparison is only needed if test is a "char*" (i.e. a null-terminated C-string), and in that case, it wouldn't be done that way. So, the two options are:
C++ style string:

std::string test = "Hello World";
if ( test == "Hello World" )
  std::cout << "test is indeed Hello World" << std::endl;
if ( test != "Hello World" )
  std::cout << "test is not Hello World" << std::endl;

C-style string:

char test[] = "Hello World";
if ((test) && (strcmp(test,"Hello World") == 0))
  std::cout << "test is indeed Hello World" << std::endl;
if ((test)  && (strcmp(test,"Hello World") != 0))
  std::cout << "test is not Hello World" << std::endl;

This is how i initialized temp, so wouldn't i need to test that it did make a string?

char testTemp[10];
		for (int i = 0; i < 10; i++)
			testTemp[i] = data.at(i);
        std::string test(testTemp, 10);

In C++ strings, they are always valid strings (but they can be empty, of course). So, in your case, you should do exactly this:

char testTemp[10];
for (int i = 0; i < 10; i++)
  testTemp[i] = data.at(i);
std::string test(testTemp, 10);
if (test != "Item Name\t")
  return data;

The reason why you see expressions to test if a string is NULL with C-style strings is that they are implemented as pointers to chars, and pointers (of any kind) should always be checked for being NULL before they are used (i.e. dereferenced). I don't know why the C# code had that as well, I guess C# is worse than I thought. In C++, you hardly ever have to use pointer types (if it is good quality code), and the standard string type in C++ reflects that fact.

Ok ty for the info :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.