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 a name for the first array, and second arrays reads names from a binary file. Then i compare them with == operator, But even though the names are the same, their values look different when i debug it. Why is this the case? 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;
}
}
You can compare char arrays that are supposed to be strings by using the c style strcmp function.
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.
You can write code for your own char array compare function. Let's start
if( sName == Student.name ) is comparing the addresses
Assuming
student::name
is achar
array or a pointer tochar
, the following expressioncompares pointers to
char
, after decayingsName
fromchar[28]
tochar*
.Given that you want to compare the strings container in these arrays, a simple option is to read the names into
std::string
and usebool operator==
:This will work for names of any length, and saves you the trouble of dealing with arrays.
The problem is in
if(sName==Student.name)
which basically compare 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 should advice working with std::string which will make this much simpler.