How To Terminate A Program If A Condition Is Not Met?

Feb 2, 2013 at 7:07pm
I am writing a simple GPA Calculator program for my C++ class. We just learned if else statements this week, so that is what the program does a lot of. If the user does not enter either an A, B, C, D, or F I want it so the program just stops there. How would I do that? I just need something that terminates the program as soon as that user error occurs. If you need any of my source code please let me know.
Feb 2, 2013 at 7:10pm
If you're in main();

1
2
if( ! ( condition ) )
    return 0;


Else, if you'rte calling functions, make the bool function() and deal with the return accordingly.
Feb 2, 2013 at 7:16pm
It would be in the main().

So you can have more than one return 0; in a program? So does that just mean the when the program reaches a return 0; it ends right there?
Feb 2, 2013 at 7:20pm
return will exit a function. In this case, it will exit the main(). Yes, you can have multiple return statements. When the first one is reached, the function exists. When the main() function exits, the program ends.
Feb 2, 2013 at 7:21pm
You can have as many as you like, I think, lol.

And yes, it would end there.

It's the same as calling a function with a lot of code in it. If you start the function and a condition isn't met, you don't want to run all the code, so you return;.

1
2
3
4
5
6
7
void func( bool d )
{
    if( ! ( d ) )
        return;

    //Load of code here that you don't want to execute if the above is incorrect.
}


The same applies to any function. (:
Feb 2, 2013 at 7:21pm
Thank you for the help!
Feb 2, 2013 at 7:24pm
Since you are limited to if else statements I would do the following:

declare variables

char getInput;

write a cout statement asking for user to type a, b, c, d, or f

cin>>getInput;

if (getInput == 'a')
do something
else if (getInput == 'b')
do something
else if(getInput == 'c')
do something
else if(getInput == 'd')
do something
else if(getInput == 'f')
do something
else
return 0;
Topic archived. No new replies allowed.