Need help allowing only 2 attempts for user

So I'm trying to make a function that determines whether a year is a leap year or not. However, I want to give the user only 2 chances to input a year and then exit the program afterwards instead of just looping the "Try again" like it does in my current code. If anybody could help point out what I'm doing wrong, I'd greatly appreciate it. Thank you!

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
#include <iostream>
using namespace std;

int isLeap(int year);

int main() {
    int year;
    int strikes;
        cout << "Please enter a year: ";
        cin >> year;
        if (isLeap(year) == 0)
            cout << year << " is not a leap year. " << endl;
        else if (isLeap(year) == 1)
            cout << year << " is a leap year. " << endl;
        else while (isLeap(year) == -1) {
        strikes++;
        if (strikes >= 2) {
            cout << "Try again! Enter a year: " << endl;
            cin >> year;
            }
        else { cout << "Bye-bye idiot! " << endl;
            return 0;
            }
    }
    return 0;
}
int isLeap(int year) {
    if (year < 0)
        return -1;
    else if (year % 4 == 0) {
        if ((year % 100 == 0)&&(year % 400 != 0))
            return 0;
        else
            return 1;
    }
    else
        return 0;
}


Example of how it should run:
1
2
3
4
5
6
7
8
9
10
11
12
Input: 1984
Output: 1984 is a leap year.

Input: -1
Output: Try again!
Input: -5
Output: Bye-bye, idiot!

Input: -5
Output: Try again!
Input: 1900
Output: 1900 is not a leap year.
Last edited on
Use a loop:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int tries = 2;
while (tries--)
{
  if user enters a year (which is any valid integer, really)
    break;
  cout << "dat aint no number!\n";
}

if (tries)
{
  cout << "foo u foo -- i give up!\n";
  return 1;
}

cout << "good job!\n" << year << " is " << (isLeap(year) ? "" : "not") << " a leap year.\n";

Hope this helps.
Topic archived. No new replies allowed.