A very simple C++ program question

I'm using Microsoft Visual Studio's C++ 2008 win 32..
How do I assign a variable to exit the program?...I didn't quite get the explanation on this web site...which was this
The exit function

exit is a function defined in the cstdlib library.

The purpose of exit is to terminate the current program with a specific exit code. Its prototype is:

void exit (int exitcode);



yes sure call me dumb but i need some help...

My program is somewhat like this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

#include <iostream>
using namespace std;

int main()
{
    int ans;

    cout<<"Hi! to exit this program pls press 1";
         cin>>ans;
    if(ans==1);
       //Here's my problem..how do i terminate the program from here? 
     //as in, the whole command prompt would dissapear if the user answers 1...

return 0;

}


My program isn't exactly that actual program...just an example of mine...but the problem is kinda like that...so could anyone help me?
Last edited on
write
if(ans==1)exit(0); //0 or any other int

you could also achieve this with
if(ans==1)return 0;
but only if you write this inside "int main()"
Last edited on
When you use exit() method, you are directly passing the return value to the operating system.
In the later case, your main() method passes the same value '0' to operating system.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;

int main() {
    int ans;
    cout << "Hi! to exit this program pls press 1:  ";
    cin >> ans;
    if (ans == 1) {
      return 0;}
    else {
      cout << "\nYou didn't press 1, press 1 to exit";
      cin >> ans;
      if (ans == 1) {
         return 0;}
      else { cout <<"you entered garbage twice... exiting anyway";
         return 0;}
}


That's what I would do... I added a few things for you to play with too.
;)
Topic archived. No new replies allowed.