0

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 :)

MrDuk
  • 16,578
  • 18
  • 74
  • 133
  • 1
    Wouldn't `buffer[0] == '@'` be just as suitable? If not, prefer C++ string operations: `b.find_first_of ("@") != string::npos` – willkill07 Mar 11 '14 at 04:35
  • 1
    How pedantic do you want this? `if (buffer && *buffer == '@')` – WhozCraig Mar 11 '14 at 04:38
  • 3
    strncmp returns 0 when the strings are equal. therefore the if condition should be: `if (strncmp(b.c_str(), c.c_str(), 1) != 0)` – LMC Mar 11 '14 at 04:51

1 Answers1

1

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();
}
hyun
  • 2,135
  • 2
  • 18
  • 20