How to compare strings
I wanted to compare a string without actually defining one of them as a string, something like this,
if (string == "add")
Do I have to declare "add"
as a string or is it possible to compare i开发者_StackOverflown 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.
You need to use strcmp
.
if (strcmp(string,"add") == 0){
print("success!");
}
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
}
精彩评论