我正在参加一个研讨会并且我已经完成了它,但我在调试方面遇到了麻烦。
程序编译并运行但我遇到的问题是,在要求用户输入数据并将其发送到显示功能后,它会显示垃圾。
我已经通过调试模式运行程序,我得出的结论是输入没有传递给我的setter函数,但在我的教授编写的代码中(他写了主要的并且问了我们在内存分配中填写一些东西)它没有要求我在main中初始化setter函数,我错过了什么?
' Weather.h'文件是设置以及显示功能在Weather类中的位置。
#include <iostream>
#include "Weather.h"
using namespace std;
using namespace sict;
int main(){
int n; //the count of days worth of weather
// initialize the weather pointer here
Weather* weather;
cout << "Weather Data\n";
cout << "=====================" << endl;
cout << "Days of Weather: ";
cin >> n;
cin.ignore();
// allocate dynamic memory here
weather = new Weather[n];
for (int i = 0; i < n; i++){
char date_description[7];
double high = 0.0, low = 0.0;
// ... add code to accept user input for
//weather
cout << "Enter date: ";
cin >> date_description;
cout << "Enter high: ";
cin >> high;
cout << "Enter low: ";
cin >> low;
}
cout << endl;
cout << "Weather report:\n";
cout << "======================" << endl;
for (int i = 0; i < n; i++){
weather[i].display();
}
// deallocate dynamic memory here
delete[] weather;
weather = (Weather*)0;
return 0;
}
/*
Output Example :
Weather Data
== == == == == == == == == == =
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 :
== == == == == == == == == == ==
Oct / 1_______15.0__10.0
Nov / 13______10.0___1.1
Dec / 15_______5.5__ - 6.5
*/
设定函数的定义(在天气中):
void Weather::set(const char* Date, double high, double low){
strcpy(date, Date);
tempHigh = high;
tempLow = low;
}
答案 0 :(得分:1)
您在weather = new Weather[n];
之后阅读数据并将其放入for循环中
您必须将它们存储到weather
。应该可以通过这个来完成:
for (int i = 0; i < n; i++){
const int store_length = 7;
char date_description[16];
char date_description_to_store[store_length];
int store_pos = 0;
double high = 0.0, low = 0.0;
// ... add code to accept user input for
//weather
cout << "Enter date: ";
cin.getline(date_description, sizeof(date_description) / sizeof(date_description[0]));
for (int i = 0; date_description[i] != '\0' && store_pos < store_length - 1; i++){
if (date_description[i] != ' ') date_description_to_store[store_pos++] = date_description[i];
}
date_description_to_store[store_pos] = '\0';
cout << "Enter high: ";
cin >> high;
cout << "Enter low: ";
cin >> low;
weather[i].set(date_description_to_store, high, low); // add this line
cin.ignore(); // add this line to ignore the new line
}
更新:您应该使用cin.getline
来读取包含空格的字符串,例如Oct / 1
。
更新2: 7个字符的缓冲区不足以读取Oct / 1
。您必须分配更多memomry或使用std::string
更新3 :您必须将Oct / 3
等输入格式转换为Jan/21
等存储格式。请注意,此代码中没有错误检查。