Comparing char array values ​​in C ++

I have a problem with something in my program. I have a char [28] array containing the names of people. I have another char [28] array that also stores names. I ask the user to enter a name for the first array, and the second array reads the names from the binary file. Then I compare them with the == operator, but even if the names are the same, their values ​​look different when I debug it. Why is this so? How can I compare these two? My sample code is as follows:

int main() { char sName[28]; cin>>sName; //Get the name of the student to be searched /// Reading the tables ifstream in("students.bin", ios::in | ios::binary); student Student; //This is a struct while (in.read((char*) &Student, sizeof(student))) { if(sName==Student.name)//Student.name is also a char[28] { cout<<"found"<<endl; break; } } 
+4
source share
5 answers

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

 sName==Student.name 

compares pointers with char , after attenuation of sName from char[28] to char* .

Given that you want to compare the container of strings in these arrays, an easy way is to read the names in 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 relieve you of problems with arrays.

+5
source

You can compare char arrays that should be strings using the c style strcmp function .

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

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

+7
source

The problem is 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 in C ++, not C, I should advise working with std :: string, which will make it a lot easier.

+3
source

if (sName == Student.name) compares addresses

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

You can write code for your own char array comparison function. Let it begin

 //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
source

All Articles