Need to end program if condition is not met

Hi everyone,

Pretty simple question here - I just want to end the program if the user doesn't meet a certain condition...I think I heard "return 0" when I read about this, but the problem is that "that" just ends the program whether or not the condition is met, and I can't move onto the next condition.

Below is the code of a part of my program, and I would obviously want to end the program after the output is given in the else statements:

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
cout << "\nPlease enter your month: \n";

cin >> month;

if (month > 0 && month <= 12)
cout << "\nMonth entered is valid. \n";

else

cout << "\nError: Month entered was not in between 0 and 12. Program ending. \n";

cout << "\nPlease enter your day: \n";

cin >> day;
if (day > 0 && day <= 31)

cout << "\nDay entered is valid. \n";

else

cout << "\nError: Day entered was not in between 0 and 31. Program ending. \n";

cout << "\nPlease enter your year (use 4-digits): \n";


cin >> year;
if (year >= 1900 && year <= 2099)

cout << "\nYear entered is valid. \n";

else

cout << "\nError: Year entered was not in between 1900 and 2099. Program ending. \n";
Last edited on
closed account (o3hC5Di1)
Hi there,

The return 0; ends the program only when it is a return statement of your main() function.

Applied to a small part of your program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int main(int argc, char** argv)
{
    cout << "\nPlease enter your day: \n";

    cin >> day;
    if (day > 0 && day <= 31)
    {
        cout << "\nDay entered is valid. \n";
    }
    else
    {
        cout << "\nError: Day entered was not in between 0 and 31. Program ending. \n";
        return 0; //This returns the main function, effectively ending the program
    }
}



Hope that helps.

All the best,
NwN
Thanks very much...I switched out the int main() and put

int main(int argc, char** argv)

but I still have the program end after valid input.
The program will end if either a return statement in main(), or if execution simply reaches the closing brace of main()

If you don't want the execution to reach that point, you may need a loop. Certainly if the user enters invalid input it is usually a good idea to go back and get the user to try again, which would involve a loop.
Yeah, I personally would do that, but that's not what the instructor asked us to do...Again, I would do it that way, as well.
I'm not sure what you are asking. The program will always end when it reaches the end of processing, unless you put something there such as a request for user to press a key.

As I understand it, you are required to end the program when invalid input is found, for which a solution given by NwN. (Not the change to int main(), that is not relevant here, but the change to the if-else.
Topic archived. No new replies allowed.