我在程序中做某事时遇到问题。我有一个保存人名的 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;
}
}
最佳答案
您可以使用 c 样式 strcmp 来比较应该是字符串的字符数组。功能。
if( strcmp(sName,Student.name) == 0 ) // strings are equal
在 C++ 中,您通常不会直接使用数组。使用 std::string类而不是字符数组,您与 == 的比较将按预期工作。
关于c++ - 在 C++ 中比较 char 数组的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15050766/