Comparing the values of char arrays in C++

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.


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.


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

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

Be careful with strcmp though

Tags:

C++

Arrays

Char