How to compare char variables (c-strings)?

后端 未结 5 1427
小鲜肉
小鲜肉 2020-12-22 10:44
#include 
using namespace std;

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

    if(word==word1){
        cout<<\"word          


        
相关标签:
5条回答
  • 2020-12-22 10:52

    Use strcmp.

    #include <cstring>
    // ...
    if(std::strcmp(word, wordl) == 0) {
    // ...
    }
    
    0 讨论(0)
  • 2020-12-22 10:53

    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.

    0 讨论(0)
  • 2020-12-22 11:00

    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;
    }
    
    0 讨论(0)
  • 2020-12-22 11:00

    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)) {
    
    0 讨论(0)
  • 2020-12-22 11:08
    #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;``
    }
    
    0 讨论(0)
提交回复
热议问题