Having an issue with an array

Hey there, so when I'm trying to get a value from my array using a variable, it prints out 0 no matter the variable value, although when I put a value in the array and try to get the element value from the array, it prints out just fine.

Edit:
I'm thinking it has something to do with the tuple.

Here's all my code:
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <tuple>

using namespace std;

int dates[3];
int months[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
string userInput1, userInput2;

tuple <int, int, int> splitString(string userInput){
	  vector<int> vect;
    stringstream ss(userInput);

    int i;

    while (ss >> i)
    {
        vect.push_back(i);

        if (ss.peek() == '/')
            ss.ignore();
    }

    for (i=0; i< vect.size(); i++){
    	dates[0] = vect.at(0);
    	dates[1] = vect.at(1);
    	dates[2] = vect.at(2);
    }

    return make_tuple(dates[0], dates[1], dates[2]);
}

int calcAge(){
   auto [day1, month1, year1] = splitString(userInput1);
   auto [day2, month2, year2] = splitString(userInput2);

   int days_delta = abs(day2-day1);
   int months_delta = abs((month2-month1) * (months[month2-month1]));
   int years_delta = abs((year2-year1) * 365);

   return abs(days_delta + (years_delta - months_delta));
}

int main (){                      
   cout<<"Enter the first date in the following format 'dd/mm/yyyy': ";
   cin >> userInput1;

   cout << "Enter the second date in the following format 'dd/mm/yyyy': ";
   cin >> userInput2;

   cout << "You are " << calcAge() << " days old" << endl;
   return 0;
 }


The "months[month2-month1]" on line 47 is returning 0, but months[<any numerical value>] returns the element value of the months array.
Last edited on
Please show compileable code with this alleged feature.
@lastchance Post edited
And what input are you giving it?

If I enter 01/02/1991 as the first date, and 01/01/1991 as the second date, month2-month1 is -1 for me, which is out of bounds.

1
2
3
4
5
int notNegative(int number){
  if (number < 0){
    return abs(number);
  }
}
This is undefined behavior for number >= 0.
Why not just use abs() directly???

Compile will warnings (-Wall in g++)
main.cpp: In function 'int notNegative(int)':
main.cpp:40:1: warning: control reaches end of non-void function [-Wreturn-type]
 }
 ^
Last edited on
What are you trying to do on line 47?
@Genado is that something you just tested or are you assuming you'll get -1? Cause I'm using abs to convert the negative numbers into positive numbers.

And my inputs are:
12/12/1999
28/01/2019

Which should give 6986
Last edited on
Yes, but you aren't returning anything for positive numbers.

If you want to do this sort of subtraction then work with cumulative days since start of year.

I hate to mention it but you've forgotten the leap years as well.
Last edited on
@lastchance I'm trying to determine the amount of days that are in that (month2-month1)

@Genado I see, I'll try to replace it with abs
Then that won't work. And if month2 is less than month1 then you will be taking an array element with a negative index!
@lastchance I just replaced the "notNegative" function with abs, so it should return a positive value, and also a positive index right ?
If month1 > month2, month2 - month1 will be negative.

If I was born in last December (12), and it is February (2), then I'm 2 months old. Not -10 or 10 or something like that.

You're also converting months to days incorrectly, you're just multiplying by the month at the index of month2 - month1, not accounting for differences in days between those two months. (Or leap years, if you care about those)

Dates (and names, languages, cultures) are really annoying for programmers to work with, so you're not alone...

_____________________________________

When you are testing your program for correctness, start with the simplest test cases first.
For example, first just differ the dates by 1 day, then 1 month, then 1 year, then do a combination of year/month/day, then try more complicated tests.
Last edited on
@Genado
If month1 > month2, month2 - month1 will be negative.

If I'm using abs, it returns a positive value of it, I just updated my code above.

But I'll try out your suggestion and start out simple.

But I'm still wondering why "months[month2-month1]" returns a value of 0 ?

Thank you.
Last edited on
Next time, please don't update your previous posts (replacing code), just post the new code below. It makes it harder for people to follow along.

If I'm using abs, it returns a positive value of it, I just updated my code above.
Not exactly, you're still just doing months[month2-month1], regardless of any outer use of abs.

But I'm still wondering why "months[month2-month1]" returns a value of 0 ?
Beause if months2-month1 is a value < 0 or >= 12, you engender undefined behavior in your program, due to an out-of-bounds array index. The result is undefined.

Another test case you should look into:
cplusplus249261>main
Enter the first date in the following format 'dd/mm/yyyy': 31/12/1991
Enter the second date in the following format 'dd/mm/yyyy': 01/01/1992
You are 395 days old
Last edited on
emilo0212,
I don't think that there is anywhere in this problem that taking the difference month2-month1 is going to help you. Months unfortunately have different numbers of days. Work with cumulative days since start of year (which will also help when you come to recognise leap years). Once you are down to years and days you should be able to use normal subtraction, "carrying" if necessary.

You don't come from a python background, do you? We don't see so many occurrences of tuples here, although we do regularly see pythonesque idioms, particularly feeding into misuse of the comma operator.
I agree, I would definitely think about the logic more instead of just doing month2 - month1, it will be wrong in many situations.

Too bad C++ doesn't have built-in DateTime objects like other languages.
Boost has a DateTime library,
https://www.boost.org/doc/libs/1_39_0/doc/html/date_time.html

C++ does inherit some time functionality from C that you can use.
https://www.tutorialspoint.com/cplusplus/cpp_date_time.htm

It might also help to think about a secondary problem: Given a date, what is the next date if I increment the day by 1? e.g. 31/12/1991 --> 01/01/1992, like in my other exampe.
Last edited on
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
#include <iostream>
#include <sstream>
#include <string>
#include <ctime>
#include <cmath>
using namespace std;

time_t getTime( string dateString )
{
   tm result{ 0, 0, 0, 0, 0, 0, 0, 0, 0 };
   for ( char &c : dateString ) if ( !isdigit( c ) ) c = ' ';
   stringstream( dateString ) >> result.tm_mday >> result.tm_mon >> result.tm_year;
   result.tm_mon--;
   result.tm_year -= 1900;
   return mktime( &result );
}

int main()
{
   const double secsPerDay = 24 * 60 * 60;
   string date1, date2;
   cout << "Enter first  date as a string (dd/mm/yyyy): ";   getline( cin, date1 );
   cout << "Enter second date as a string (dd/mm/yyyy): ";   getline( cin, date2 );
   cout << "Days difference = " << (int)( 0.5 + abs( difftime( getTime( date1 ), getTime( date2 ) ) / secsPerDay ) );
}


Enter first  date as a string (dd/mm/yyyy): 30/01/2019
Enter second date as a string (dd/mm/yyyy): 15 10 2016
Days difference = 837 


Crikey! Have I really been on the forum that long?
Last edited on
Topic archived. No new replies allowed.