比较C++中char数组的值

Comparing the values of char arrays in C++

本文关键字:数组 char C++ 比较      更新时间:2023-10-16

我有一个保存人名的char[28]数组。我有另一个char[28]数组,它也保存名称。我要求用户输入第一个数组的名称,第二个数组从二进制文件中读取名称。然后将它们与==算子进行比较。但是,即使名称相同,当我调试它时,它们的值看起来也不同。为什么会出现这种情况?我该如何比较这两个?我的示例代码如下:

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;
        }
    }
}

您可以使用c风格的strcmp函数来比较应该是字符串的char数组。

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

在C++中,通常不直接使用数组。使用std::string类而不是字符数组,与==的比较将按预期进行。

假设student::namechar数组或指向char的指针,则以下表达式

sName==Student.name

在将sNamechar[28]衰减到char*之后比较到char的指针。

假设您想比较这些数组中的字符串容器,一个简单的选项是将名称读取到std::string并使用bool operator==:

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

这将适用于任何长度的名称,并为您省去处理数组的麻烦。

通常,如果(sName==Student.name)正在比较地址。

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

不过要小心strcmp。

问题出在if(sName==Student.name)中,它主要比较数组的地址,而不是它们的值
更换为(strcmp(sName, Student.name) == 0)

但总的来说,您使用的是C++,而不是C,我建议使用std::string,这会让这件事变得更简单。

您可以为自己的char数组比较函数编写代码。让我们启动

//Return 0 if not same other wise 1
int compare(char a[],char b[]){
    for(int i=0;a[i]!='';i++){
        if(a[i]!=b[i])
            return 0;
    }
    return 1;
}

我不能留下评论,这是对habib比较字符串开头的答案的调整:

int compare(char a[], char b[]) {
    for(int i = 0; strlen(a) < strlen(b) ? a[i] != '' : b[i] != ''; i++) {
        if(a[i] != b[i])
            return 0;
    }
    return 1;
}

我需要这个来比较不包括GET参数的webrequest查询。