【问题标题】:Function that searches object array for string and returns corresponding value在对象数组中搜索字符串并返回相应值的函数
【发布时间】:2020-06-12 19:39:18
【问题描述】:

我需要创建一个函数,该函数接受输入的日期并在高/低温数据集中搜索匹配日期,然后返回该日期对应的最低温度。输入日期的格式与数组中的格式相匹配,因此这不是问题。目前,该函数每次都返回 0。如果我不得不猜测,我认为 if 语句或我的 getDate 函数有问题。

double findLow(const char* date, const Weather *data, int dataSize) {
    for (int i = 0; i < dataSize; i++) {
        // If date matches, return lowest temp
        if (date == data[i].getDate()) {
            return data[i].getLow();
        }   
    }
    return 0.0;
}

这是我的其他功能:

const char* Weather::getDate() const {
    return &date[0];
}

double Weather::getLow() const {
    return lowTemp;
}

提前致谢。

【问题讨论】:

  • 您无法使用 == 比较 const char* 类似的字符串。这是使用strcmp 完成的(尽管它提出了一个问题,为什么你不使用std::string 代替)
  • 看起来你正在检查指针是否相等

标签: c++


【解决方案1】:

date == data[i].getDate()

你不能那样比较指针。如果无论如何都必须使用数组,最好使用 std::string (大多数日期表示应该使用专用类)。

【讨论】:

    【解决方案2】:

    使用std::string 代替const char*,否则只比较指针而不是字符串内容。

    class Weather
    {
    // ...
    private:
        std::string date;
    public:
        const std::string& getDate() const { return date; }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-06
      • 2021-04-27
      • 1970-01-01
      • 2014-07-26
      • 2021-09-27
      • 2011-04-23
      相关资源
      最近更新 更多