比较C++中char数组的值 [英] Comparing the values of char arrays in C++

查看:23
本文介绍了比较C++中char数组的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的程序中做某事时遇到问题.我有一个保存人名的 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::name 是一个 char 数组或指向 char 的指针代码>,下面的表达式

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

sName==Student.name

比较指向 char 的指针,在将 sNamechar[28] 衰减到 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.

这篇关于比较C++中char数组的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆