如何比较char变量(c-strings)?

Wiz*_*ard 0 c++ if-statement compare

#include <iostream>
using namespace std;

int main() {
    char word[10]="php";
    char word1[10]="php";

    if(word==word1){
        cout<<"word = word1"<<endl;
    }

return 0;
}
Run Code Online (Sandbox Code Playgroud)

我不知道如何比较两个char字符串以检查它们是否相等.我目前的代码不起作用.

Pub*_*bby 9

使用strcmp.

#include <cstring>
// ...
if(std::strcmp(word, wordl) == 0) {
// ...
}
Run Code Online (Sandbox Code Playgroud)


tro*_*foe 7

std::string改为使用对象:

#include <iostream>
#include <string>
using namespace std;

int main() {
    string word="php";
    string word1="php";

    if(word==word1){
        cout<<"word = word1"<<endl;
    }

return 0;
}
Run Code Online (Sandbox Code Playgroud)


Mic*_*ker 6

为了证明c ++标签的合理性,你可能想要声明wordword1as std::string.根据需要进行比较

if(!strcmp(word,word1)) {
Run Code Online (Sandbox Code Playgroud)