How to compare char variables (c-strings)?

浪子不回头ぞ 提交于 2019-12-18 09:44:22

问题


#include <iostream>
using namespace std;

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

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

return 0;
}

I don't know how to compare two char strings to check they are equal. My current code is not working.


回答1:


Use std::string objects instead:

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

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

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

return 0;
}



回答2:


Use strcmp.

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



回答3:


To justify c++ tag you'd probably want to declare word and word1 as std::string. To compare them as is you need

if(!strcmp(word,word1)) {



回答4:


word and word1 in your submitted code are pointers. So when you code:

word==word1

you are comparing two memory addresses (which isn't what you want), not the c-strings they point to.




回答5:


#include <iostream>
**#include <string>** //You need this lib too

using namespace std;

int main() 
{

char word[10]="php";
char word1[10]="php";

**if(strcmp(word,word1)==0)** *//if you want to validate if they are the same string*
    cout<<"word = word1"<<endl;
*//or*
**if(strcmp(word,word1)!=0)** *//if you want to validate if they're different*
    cout<<"word != word1"<<endl;

return 0;``
}


来源:https://stackoverflow.com/questions/8355465/how-to-compare-char-variables-c-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!