【发布时间】: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有关。你能显示那个代码吗? -
一个常见问题是正在比较的字符串中的一个尾随换行符。这取决于数据的来源,但您没有向我们展示这一点。
-
您是否考虑过在调试器中单步执行代码并查看正在比较的字符串?
-
如果您只是使用调试器单步执行代码,这个问题应该很明显。您会看到您的输入不正确。