【问题标题】:Problems with strcmp() [closed]strcmp() 的问题 [关闭]
【发布时间】:2016-02-08 03:39:27
【问题描述】:

我不确定它是 strcmp 还是函数本身,但有些东西不起作用。 这是 main 函数中的代码。

double findLow(const char* date, const Weather *data, int dataSize) {
    int i, o;
    for (i = 0; i < dataSize; i++) {
        o = strcmp(data[i].date(), date); //testing
        cout << o << ' ' << data[i].date() << date << endl;  //testing
        if (strcmp(data[i].date(),date) == 0)
            return data[i].low();       
    }
    return 0.0;
}

这是 date() 函数(公共成员函数)的代码。

const char* Weather::date() const {
    return _dateDescription;
}

由于某种原因,即使字符串匹配,strcmp 函数也会返回 1。 dateDescription 是一个由 7 个字符组成的 C 风格字符串,data[i].date() 尝试查找与 dateDescription 格式相同的日期。

cout 也不会显示 data[i].date()

编辑:当我运行完整的代码时,它看起来像这样:

Days of Weather: 3
Enter date: Oct/1
Enter high: 15
Enter low : 10
Enter date: Nov/13
Enter high: 10
Enter low : 1.1
Enter date: Dec/15
Enter high: 5.5
Enter low : -6.5

Weather report:
Date        high  low
======================
Oct/1_______15.0__10.0
Nov/13______10.0___1.1
Dec/15_______5.5__-6.5

Enter the date you are looking for: Nov/13
1 Oct/15
1 Nov/13
1 Dec/15
Low temperature: 0.0(meant to show the low temp of the date requested)

没有显示的是我测试的日期变量。 Paste of the full code

【问题讨论】:

  • 由于某种原因,即使字符串匹配,strcmp 函数也会返回 1——显然,字符串不匹配。要么你错了,要么你有一个错误的编译器。
  • "cout 也不会显示数据[i].date()",那么你的问题不在于strcmp。这可能与_dateDescription 的设置方式有关,甚至可能与data 有关。你能显示那个代码吗?
  • 一个常见问题是正在比较的字符串中的一个尾随换行符。这取决于数据的来源,但您没有向我们展示这一点。
  • 您是否考虑过在调试器中单步执行代码并查看正在比较的字符串?
  • 如果您只是使用调试器单步执行代码,这个问题应该很明显。您会看到您的输入不正确。

标签: c++ strcmp


【解决方案1】:

这是你的问题:

cin >> query;
//(in this example stored in char query[7])
// and display the found low temprature.

cin.getline(query, 7, '\n');

你从标准输入读入query...然后你再次读入它。第二次,那行除了'\n' 什么都没有了——所以它读入一个空字符串。

我删除了cin.getline 并得到了合理的结果。

检测这种情况的方法是使用调试器逐步检查,并注意query"",而不是输入的日期。

【讨论】:

    猜你喜欢
    • 2018-03-12
    • 1970-01-01
    • 1970-01-01
    • 2018-09-14
    • 1970-01-01
    • 1970-01-01
    • 2014-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多