how to compare string?

I have a condition and I want to evaluate the it as true when dirname is "0". Now it does not print any text.

1
2
3
4
5
char dirname [260] = ".";
if ( dirname == "." || dirname == ".." )
        {puts("Not a directory!!!");
        exit(1);
        }


How to do this when the strings are not same type?
Last edited on
dirname is a pointer to your dirname array. You're trying to compare a memory address with a string literal, this doesn't make sense.

But the way you're doing it, you'd have to use strcmp() and see if that function returns 0.
http://www.cplusplus.com/reference/cstring/strcmp/ (see the example, you need # <string.h>)

If you were using std::string instead of char arrays, you could easily do (dirname == ".") because of C++ operator overloading.
Here's how you'd do it with std::string
(Edit: but judging from the other posts it looks like you're coding in C so I guess you can't use this)
1
2
3
4
5
6
#include <string>
std::string dirname = ".";
if (dirname == "." || dirname == "..")
{
    //not a directory, etc
}
Last edited on
Topic archived. No new replies allowed.