Reputation: 17708
What is the correct C++ way of comparing a memory buffer with a constant string - strcmp(buf, "sometext")
? I want to avoid unnecessary memory copying as the result of creating temporary std::string objects.
Thanks.
Upvotes: 4
Views: 6998
Reputation: 49729
strcmp is good if you know the contents of your buffer. std::strncmp
might give you a little more security against buffer overflows.
Upvotes: 4
Reputation: 100718
If you're just checking for equality, you may be able to use std::equal
#include <algorithms>
const char* text = "sometext";
const int len = 8; // length of text
if (std::equal(text, text+len, buf)) ...
of course this will need additional logic if your buffer can be smaller than the text
Upvotes: 4
Reputation: 347416
I would use memcmp, and as the last parameter, use the minimum of the 2 sizes of data.
Also check to make sure those 2 sizes are the same, or else you are simply comparing the prefix of the shortest one.
Upvotes: 1
Reputation: 7457
You may do it like,
const char* const CONST_STRING = "sometext";
strcmp(buf,CONST_STRING);
Upvotes: 0
Reputation: 545865
strcmp
works fine, no copy is made. Alternatively, you could also use memcmp
. However, when in C++, why not use std::string
s?
Upvotes: 1