jackhab
jackhab

Reputation: 17708

compare buffer with const char* in C++

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

Answers (5)

schnaader
schnaader

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

Ferruccio
Ferruccio

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

Brian R. Bondy
Brian R. Bondy

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

Canopus
Canopus

Reputation: 7457

You may do it like,

const char* const CONST_STRING = "sometext";

strcmp(buf,CONST_STRING);

Upvotes: 0

Konrad Rudolph
Konrad Rudolph

Reputation: 545865

strcmp works fine, no copy is made. Alternatively, you could also use memcmp. However, when in C++, why not use std::strings?

Upvotes: 1

Related Questions