Comparing the values of char arrays in C++(比较 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
在将 sName 从 char[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.
这篇关于比较 C++ 中 char 数组的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:比较 C++ 中 char 数组的值
				
        
 
            
        基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
 - 我有静态或动态 boost 库吗? 2021-01-01
 - 常量变量在标题中不起作用 2021-01-01
 - 如何检查GTK+3.0中的小部件类型? 2022-11-30
 - 如何在 C++ 中初始化静态常量成员? 2022-01-01
 - 在 C++ 中计算滚动/移动平均值 2021-01-01
 - C++结构和函数声明。为什么它不能编译? 2022-11-07
 - 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
 - 这个宏可以转换成函数吗? 2022-01-01
 - 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				