c++ - 在 C++ 中比较 char 数组的值

标签 c++ arrays char

我在程序中做某事时遇到问题。我有一个保存人名的 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 来比较应该是字符串的字符数组。功能。

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

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

关于c++ - 在 C++ 中比较 char 数组的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15050766/

相关文章:

c++ - 快速检查 C++ 中的递增/递减运算符

java - 无法使用带有java的gson反序列化未知类型的数组

C 将 char append 到 char*

c++ - D3D11 中是否有等同于 OpenGL glVertexAttrib() 的函数?

c++ - 为什么枚举会隐式转换为 std::string?

java - 考虑内存的文件比较

c - (C语言)检查字符串中的元音

c++ - 字符* 替换为字符*

java - 找不到 char 的符号

c++ - CMake 配置等同于 GCC 选项