【问题标题】:File not loading properly in C文件未在 C 中正确加载
【发布时间】:2015-03-19 14:46:47
【问题描述】:

我正在尝试使用指向数组的指针和定义的目标来比较字符串。

string destination;

int flightcompare(Flights FDA[], String destination)
{
    int j=0;
    Flights founddestination[10];
    for (int i=0;i<MAXARRAYSIZE;i++)
    {
        (strcmp(Flight *FDA[i]->destination,destination)==0);
        founddestination[j]= FDA[i];
        j++;
    }
    return 1;
}

【问题讨论】:

    标签: c string compare


    【解决方案1】:

    我不确定编程语言,但我假设它是一种以string 作为数据类型的语言。

    在您的代码中,末尾有一个分号

    strcmp(Flight *FDA[i]->destination,destination)==0);
    

    使用strcmpredundant。 删除该分号。 另外你不需要通过Flight*strcmp 因此,通过这些修改,函数应该如下所示:

    int flightcompare(Flights FDA[], String destination)
    {
            int j=0;
            Flights founddestination[10];
            for (int i=0;i<MAXARRAYSIZE;i++)
            {
                if(strcmp(FDA[i]->destination,destination)==0)
                {
                    founddestination[j]= FDA[i];
                    j++;
                    if(j >= 10)
                    {
                       break; // Stop Looping as Array is full
                    }
                }
            }
        return j; // Return Count of the Flights found.
    }
    

    【讨论】:

      【解决方案2】:

      您的strcmp 行没有任何意义,因为您没有检查作为比较结果的布尔值。
      一般来说,应该放在if 语句中。

      还有另一个问题,因为不需要将字符串对象与strcmp 进行比较。
      您可以将它们与运营商== 进行比较。

      if (FDA[i].destination == destination) {
          // they're equal -> do something
      } else {
          // they're not equal -> do something else
      }
      

      假设Flights 类型有一个“目标”公共成员。


      此外,如果您不使用它,为什么要将它们放在founddestination 数组中?以及返回 int 的目的是什么?

      如果您想知道是否有任何不匹配的目的地,您可以返回一个布尔值。
      如果您想返回相等目的地/不相等目的地的数量,您可以将它们计算在一个 int 中。

      假设你的目标是我要写的布尔解决方案:

      bool flightcompare(Flights FDA[], String destination) {
          for (int i = 0; i < MAXARRAYSIZE; ++i) {
              if (FDA[i].destination != destination) {
                  return false;
              }
          }
          return true;
      }
      

      如果您想返回匹配航班的数量,我会写:

      int flightcompare(Flights FDA[], String destination) {
          int count = 0;
          for (int i = 0; i < MAXARRAYSIZE; ++i) {
              if (FDA[i].destination == destination) {
                  ++count;
              }
          }
          return count;
      }
      

      【讨论】:

        猜你喜欢
        • 2023-04-03
        • 1970-01-01
        • 2023-03-04
        • 1970-01-01
        • 2010-12-10
        • 1970-01-01
        • 2011-08-12
        • 2015-11-01
        • 1970-01-01
        相关资源
        最近更新 更多