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?
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?
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.
string
is a std::string
object, this will work, but then strcmp()
would not have worked. Which is it? I'm dying to know! :)
–
Icarus char*
! –
Gervase if( strcmp(string.c_str(),"add")==0 ) {...}
would work. –
Gervase if (strcmp(string, "add") == 0) { ... }
worked. –
Icarus string
is a char*
, in which case this is the wrong answer. I was hoping Anon would clarify that. –
Icarus string
is a char*
? What should I do? –
Hight You need to use strcmp
.
if (strcmp(string,"add") == 0){
print("success!");
}
strcmp()
is a C function which takes pointers to const char*
as its arguments. It works in this case because the std::string
object is converted back into a const char*
, but this is not the best way to do things in C++ –
Icarus std::string
does not implicitly convert to const char*
, you need to call s.c_str()
for that. But according to the question "without defining either one as a string", string
isn't a std::string
to begin with. –
Adria 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
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;
}
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
}
© 2022 - 2025 — McMap. All rights reserved.
string
? Is it a C++std::string
object, or simply aconst char*
? – Icarus"
(double quotes), single quotes are for single char literals. – Loxodromic