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++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
