我在程序中做某事有疑问。我有一个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;
}
}
答案 0 :(得分:14)
您可以使用c样式strcmp函数比较应该是字符串的char数组。
if( strcmp(sName,Student.name) == 0 ) // strings are equal
在C ++中,您通常不直接使用数组。使用std::string类而不是字符数组,您与==的比较将按预期工作。
答案 1 :(得分:7)
假设student::name
是char
数组或指向char
的指针,则以下表达式
sName==Student.name
在char
从sName
衰减到char[28]
之后,将指针与char*
进行比较。
鉴于您要比较这些数组中的字符串容器,一个简单的选项是将名称读入std::string
并使用bool operator==
:
#include <string> // for std::string
std::string sName;
....
if (sName==Student.name)//Student.name is also an std::string
这适用于任何长度的名称,并为您节省处理数组的麻烦。
答案 2 :(得分:4)
问题出在if(sName==Student.name)
,它基本上比较了数组的地址,而不是它们的值
将其替换为(strcmp(sName, Student.name) == 0)
但总的来说,你正在研究C ++,而不是C,我应该建议使用std :: string来使这更简单。
答案 3 :(得分:2)
if(sName == Student.name)正在比较地址
if( strcmp( sName, Student.name ) == 0 {
/ * the strings are the same */
}
答案 4 :(得分:0)
您可以为自己的char数组比较函数编写代码。 让我们开始吧
//Return 0 if not same other wise 1
int compare(char a[],char b[]){
for(int i=0;a[i]!='\0';i++){
if(a[i]!=b[i])
return 0;
}
return 1;
}