比较C ++中的char数组的值 [英] Comparing the values of char arrays in 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::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数组的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!