比较 C++ 中 char 数组的值

2022-01-12 00:00:00 arrays char c++

我在我的程序中做某事有问题.我有一个 char[28] 数组来保存人名.我还有另一个 char[28] 数组,它也保留名称.我要求用户输入第一个数组的名称,第二个数组从二进制文件中读取名称.然后我将它们与 == 运算符进行比较,但即使名称相同,当我调试时它们的值看起来也不同.为什么会这样?我如何比较这两者?我的示例代码如下:

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

推荐答案

假设 student::namechar 数组或指向 char,如下表达式

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

sName==Student.name

在将 sNamechar[28] 衰减为 char* 之后,比较指向 char 的指针.

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

鉴于您想比较这些数组中的字符串容器,一个简单的选择是将名称读入 std::string 并使用 bool operator==:

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.

相关文章