【问题标题】:Comparing the values of char arrays in C++比较 C++ 中 char 数组的值
【发布时间】:2013-02-09 15:21:54
【问题描述】:

我在我的程序中做某事有问题。我有一个 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;
    }
}

【问题讨论】:

  • 如果某人的名字有 29 个字符会怎样?
  • student::name的类型是什么?

标签: c++ arrays char


【解决方案1】:

您可以使用 c 风格的 strcmp 函数来比较应该是字符串的 char 数组。

if( strcmp(sName,Student.name) == 0 ) // strings are equal

在 C++ 中,您通常不直接使用数组。使用 std::string 类而不是字符数组,您与 == 的比较将按预期进行。

【讨论】:

    【解决方案2】:

    假设student::namechar数组或指向char的指针,则如下表达式

    sName==Student.name
    

    在将 sNamechar[28] 衰减到 char* 之后,比较指向 char 的指针。

    鉴于您想比较这些数组中的字符串容器,一个简单的选择是将名称读入std::string 并使用bool operator==

    #include <string> // for std::string
    
    std::string sName;
    ....
    
    if (sName==Student.name)//Student.name is also an std::string
    

    这适用于任何长度的名称,并且省去了处理数组的麻烦。

    【讨论】:

    • 您的解决方案不只是像用户 pahoughton 在他的回答 stackoverflow.com/a/15050796/433718 中所说的那样比较地址吗?
    • @OneWorld 不,它使用== 运算符重载之一,采用std::stringchar*
    【解决方案3】:

    if( sName == Student.name ) 正在比较地址

    if( strcmp( sName, Student.name ) == 0 { 
      / * the strings are the same */
    }
    

    请小心使用 strcmp

    【讨论】:

    • 您对比较失败的原因是正确的,但是告诉某人在 C++ 程序中使用 strcmp 是个坏建议。
    【解决方案4】:

    问题出在if(sName==Student.name),它基本上比较的是数组的地址,而不是它们的值。
    将其替换为(strcmp(sName, Student.name) == 0)

    但总的来说,您使用的是 C++,而不是 C,我建议您使用 std::string,这将使这更简单。

    【讨论】:

      【解决方案5】:

      您可以为自己的字符数组比较函数编写代码。 开始吧

      //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;
      }
      

      【讨论】:

      • 循环中的条件应检查ab 是否为\0。你不知道哪个字符串会更短。
      【解决方案6】:

      我无法发表评论,调整 habib 的比较字符串开头的答案:

      int compare(char a[], char b[]) {
          for(int i = 0; strlen(a) < strlen(b) ? a[i] != '\0' : b[i] != '\0'; i++) {
              if(a[i] != b[i])
                  return 0;
          }
          return 1;
      }
      

      我需要这个来比较不包括 GET 参数的 webrequest 查询。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多