Inputing Days to get months

I am having trouble on compiling this which ask for user to input an integer between 1 and 365, and it output the month and day that the integer fall under.
I keep getting seg fault.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

string get_date(int);
 int main()
     {
 14     int input;
 15
 16     cout <<"Enter the nth day of the year: ";
 17     cin >> input;
 18
 19     get_date(input);
 20
 21     cout <<"Day " << input << " is " << get_date(input) << endl;
 22
 23     return 0;
 24 }
 25
 26 string get_date(int day)
 27 {
 28     int month;
 29     int day_of_month;
 30
 31     string months [12] = { "Jan", "Feb", "Mar", "Apr", "May",
 32        "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
 33    int days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
 34
 35    for(int i = 0; i < 12; i++)
 36    {
 37         months[i] = day % days[i];
 38         if (days - days[i] > 0)
 39             day_of_month = day - days[i];
 40
 41    }
 42
 43    return months[month] + " " + to_string(day_of_month);
 44
 45 }



Output

Enter the nth day of the year: 5
Day 5 is Jan 5
I presume the seg fault is either from the use of the variable month in line 43 (which hasn't been given a value at this point) or the fact that you are trying to assign an integer to a string in line 37.

I can't fathom out what you are intending in lines 35 - 38. You need to decide HOW you are to identify the month and try a few numerical values by hand BEFORE you try coding it. Line 39 would only be vaguely in the right direction if it was (a) outside of the loop and (b) the quantity days[i] didn't hold days in the month but the cumulative number of days prior to that month.

Think about your algorithm first - then try coding it.
Topic archived. No new replies allowed.