Search code examples
c++charcomparestrncmp

For the life of me, I can't compare the first character of this array


All I want to do is pass in a char* buffer and compare that to a literal string "@" -- why is this so difficult for me.

    char* buffer = "@3702";
    string b(buffer);
    string c("@");

    if (strncmp(b.c_str(), c.c_str(), 1) == 0)
    {
        perror("Buffer malformated!");
        return false;
    }

What do I not understand about this?

Edit: haaaa, != not == whoops :)


Solution

  • If you just want to compare char*and use strncmp(), you don't need to use stl string for this.

    int main()
    {
        char* buffer = "@3702";
        char* c = "@";
    
        if (strncmp(buffer, c, strlen(c)) == 0)
        {
            //same string
            return true;
        }
        else
        {
            //not same string
            return false;
        }
    
        getchar();
    }
    

    And, remember char[] can convert to char*, so in this case, above code is similar to below code.

    int main()
    {
        char buffer[] = "@3702";
        char c[] = "@";
    
        if(buffer[0] == c[0])
        {
            //same string
            return true;
        }
        else
        {
            //not same string
            return false;
        }
    
        getchar();
    }