Reputation: 357
I wanted to compare a string to a string literal; something like this:
if (string == "add")
Do I have to declare "add"
as a string or is it possible to compare in a similar way?
Upvotes: 29
Views: 147126
Reputation: 39385
std::string
std::string
has an operator overload that allows you to compare it to another string.
std::string string = "add";
if (string == "add") // true
std::string_view
(C++17)If one of the operands isn't already a std::string
or std::string_view
, you can wrap either operand in a std::string_view
. This is very cheap, and doesn't require any dynamic memory allocations.
#include <string_view>
// ...
if (std::string_view(string) == "add")
// or
if (string == std::string_view("add"))
// or
using namespace std::string_literals;
if (string == "add"sv)
strcmp
(compatible with C)If neither of those options is available, or you ned to write code that works in both C and C++:
#include <string.h>
// ...
const char* string = "add";
if (strcmp(string, "add") == 0) // true
Upvotes: 0
Reputation: 119106
In C++ the std::string
class implements the comparison operators, so you can perform the comparison using ==
just as you would expect:
if (string == "add") { ... }
When used properly, operator overloading is an excellent C++ feature.
Upvotes: 66
Reputation: 514
We use the following set of instructions in the C++ computer language.
Objective: verify if the value inside std::string
container is equal to "add":
if (sString.compare(“add”) == 0) { //if equal
// Execute
}
Upvotes: -1
Reputation: 6695
You could use strcmp()
:
/* strcmp example */
#include <stdio.h>
#include <string.h>
int main ()
{
char szKey[] = "apple";
char szInput[80];
do {
printf ("Guess my favourite fruit? ");
gets (szInput);
} while (strcmp (szKey,szInput) != 0);
puts ("Correct answer!");
return 0;
}
Upvotes: -1
Reputation: 7953
You need to use strcmp
.
if (strcmp(string,"add") == 0){
print("success!");
}
Upvotes: 7