Reputation: 23
I am new to C++ and am working on a question for class:
4. Annual Rainfall Report
Write a program that displays the name of each month in a year and its rainfall amount, sorted in order of rainfall from highest to lowest. The program should use an array of structures, where each structure holds the name of a month and its rainfall amount. Use a constructor to set the month names. Make the program modular by calling on different functions to input the rainfall amounts, to sort the data, and to display the data.
Here is the code I have so far:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
struct Month //defining the structure
{
string name;
double rain;
Month(string name = "", double rain = 0){} //constructor
};
const int SIZE = 12; //12 months
//initializing each structure with the name
Month month[SIZE] = { Month("January", 0), Month("February",0), Month("March", 0),
Month("April", 0), Month("May", 0), Month("June", 0),
Month("July", 0), Month("August", 0), Month("September", 0),
Month("October", 0), Month("November", 0), Month("December",0)};
void rainIn();
void sort();
void display();
int main() {
rainIn();
display();
return 0;
}
void rainIn()
{
for (int i = 0; i < SIZE; ++i)
{
cout << "Please enter the rainfall for " << month[i].name << ": ";
cin >> month[i].rain;
}
}
void sort() //will write later
{ }
void display()
{
for (int i = 0; i < SIZE; ++i)
{
cout << month[i].name << month[i].rain << endl;
}
}
The problem I am having is that the name of the month is not displayed when I try to call it. Am I initializing the array incorrectly?
After reading the comments and answers, I developed a "Minimal, Complete, Verifiable" example:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
struct Month
{
string name;
double rain;
Month(string n = "", double r = 0) {}
};
Month month("January", 12);
int main() {
cout << month.name << " had " << month.rain << " inches of rain. " << endl;
return 0;
}
Which still gave me the same problem. I changed the constructor (and added the member initialization list) as shown:
Month(string n = "", double r = 0) : name{n}, rain{r} {}
and it worked.
Upvotes: 2
Views: 494
Reputation: 50101
The problem is not the array, but that the constructor does not actually set the member variables to the input values. Try this instead:
Month(string name = "", double rain = 0) : name{name}, rain{rain} {} //constructor
This syntax is called "member initialization list". If it should look foreign to you, have a look at this.
Upvotes: 4