-3

I am tring to make a day counter which counts the days between two dates but the check doesn't work as i would like to. The problem is that it passes any value I give it for example it thinks there are 41 days in one month. Thank you for your help!

cout << "Please give the two dates!\n";
    cin >> year1 >> m1 >> d1 >> year2 >> m2 >> d2;

    if (1 <= year1 <= 9999 &&
        1 <= year2 <= 9999 &&
        1 <= m1 <= 12 &&
        1 <= m2 <= 12 &&
        1 <= d1 <= 31 &&
        1 <= d2 <= 31 )
    {
        cout << "ok";
    }
    else
    {
        cout << "notOK";
    }
  • 5
    Please consider purchasing a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) for beginners. – Mike Borkland Jun 16 '18 at 12:37
  • The date-check effort is not interesting. I think you can not easily count days from one date to the other, so it will also not be useful. You are aware of leap days? and the 4 century correction? Calendar conversions are non-trivial. IMHO, the most convenient approach is to use std::time() (returns current calendar time encoded as std::time_t object on success), Since every day (even leap day) is 24 hrs, don't bother converting to localtime(), just use modulo arithmetic. The C++ choice would involve chrono, which is important to learn, so be sure to give that a try, too. – 2785528 Jun 16 '18 at 19:54

2 Answers2

3

consider

1<=year1<=9999

should be 1<=year1&&year1<=9999

the reason is C++ is not math language.

1<=year1

is an expression returning a boolean value, which is either true or false,then compare the boolean result with 9999 is wrong.

Other lines also have this problem, correct it.

con ko
  • 1,368
  • 5
  • 18
  • @KillzoneKid Yes, I mean in logic, it must be wrong. But the code, is, of course, well-formed. – con ko Jun 16 '18 at 12:43
1

Try this:

cout << "Please give the two dates!\n";
    cin >> year1 >> m1 >> d1 >> year2 >> m2 >> d2;
    if ((1 <= year1) && (year1 <= 9999) &&
        ((1 <= year2) && (year2 <= 9999)) &&
        ((1 <= m1) && (m1 <= 12)) &&
        ((1 <= m2) && (m2 <= 12)) &&
        ((1 <= d1) && (d1 <= 31)) &&
        ((1 <= d2) && (d2 <= 31)))
    {
        cout << "ok\n";
    }
    else
    {
        cout << "notOK";
    }
}
suren
  • 7,817
  • 1
  • 30
  • 51