Hello there. I'm working with dynamic memory right now and I wrote a code. I got a problem with my output and dont know how to fix it. I've 3 files w3.cpp weather.h weather.cpp. I assume that the problem is in the w3.cpp file. Could you help me to fix it? The problem : every time I run my code. The second/3rd/4th etc date is missing. The compiler doesnt let me to input something.
Code:
//My input/output
Weather Data
=====================
Days of Weather: 3
Enter date:
May 10
Enter high:
15
Enter low :
10
Enter date: // THIS IS MY PROBLEM
Enter high:
19
Enter low :
15
Enter date:
Enter high:
20
Enter low :
19
Weather report:
==================
May 10 15 10
19 15
20 19
Code:
//w3.cpp
//w3.cpp
//Last changes : 30/5/2015
#include <iostream>
#include <string.h>
#include "weather.h"
using namespace std;
int main(){
int n;
Weather* weather = NULL ;
cout << "Weather Data\n";
cout << "=====================" << endl;
cout << "Days of Weather: ";
cin >> n;
cin.ignore();
// allocate dynamic memory here
weather = new (nothrow) Weather[n];
for(int i = 0; i < n; i++){
char date_description[31];
double high=0.0, low=0.0;
cout << "Enter date:\n";
cin.getline(date_description,31);
//cin >> date_description;
cout << "Enter high:\n";
cin >> high;
cout <<"Enter low :\n";
cin >> low;
weather[i].set(date_description,high,low);
strcpy( date_description, "" );
}
cout << endl;
cout << "Weather report:\n";
cout << "==================" << endl;
for(int i = 0; i < n; i++){
weather[i].display();
cout << endl;
}
delete[] weather;
weather = NULL;
return 0;
}
// cout<<left<< setfill(" ")<<variables;
Code:
//weather.h
//Last changes: 30/05/2015
class Weather{
char _weather_array[31];
double _high;
double _low;
public:
void set(char (&date_description)[31],double &high,double &low);
void display() const;
};
Code:
//weather.cpp
//Last changes : 30/05/2015
#include <iostream>
#include <string.h>
#include "weather.h"
using namespace std;
void Weather::set(char (&date_description)[31],double &high,double &low){
strcpy (_weather_array,date_description);
/*for (int i = 0; i<31;i++){
_weather_array[i] = date_description[i];
}*/
_high = high;
_low = low;
}
void Weather::display() const{
cout << _weather_array<<" "<< _high<<" "<<_low<<" "<< endl;
}