Comparing the values of char arrays in C++

后端 未结 5 1889
广开言路
广开言路 2021-01-02 02:38

I have problem about doing something in my program. I have a char[28] array keeping names of people. I have another char[28] array that also keeps names. I ask user to enter

相关标签:
5条回答
  • 2021-01-02 02:57

    You can write code for your own char array compare function. Let's start

    //Return 0 if not same other wise 1
    int compare(char a[],char b[]){
        for(int i=0;a[i]!='\0';i++){
            if(a[i]!=b[i])
                return 0;
        }
        return 1;
    }
    
    0 讨论(0)
  • 2021-01-02 03:11

    if( sName == Student.name ) is comparing the addresses

    if( strcmp( sName, Student.name ) == 0 { 
      / * the strings are the same */
    }
    

    Be careful with strcmp though

    0 讨论(0)
  • 2021-01-02 03:15

    Assuming student::name is a char array or a pointer to char, the following expression

    sName==Student.name
    

    compares pointers to char, after decaying sName from char[28] to char*.

    Given that you want to compare the strings container in these arrays, a simple option is to read the names into std::string and use bool operator==:

    #include <string> // for std::string
    
    std::string sName;
    ....
    
    if (sName==Student.name)//Student.name is also an std::string
    

    This will work for names of any length, and saves you the trouble of dealing with arrays.

    0 讨论(0)
  • 2021-01-02 03:21

    You can compare char arrays that are supposed to be strings by using the c style strcmp function.

    if( strcmp(sName,Student.name) == 0 ) // strings are equal
    

    In C++ you normally don't work with arrays directly. Use the std::string class instead of character arrays and your comparison with == will work as expected.

    0 讨论(0)
  • 2021-01-02 03:21

    The problem is in if(sName==Student.name) which basically compares the address of the arrays, not their values.
    Replace it with (strcmp(sName, Student.name) == 0)

    But in general, you are working on C++, not C, I would advise working with std::string which will make this much simpler.

    0 讨论(0)
提交回复
热议问题