-1

I am writing a program where the user enters how much money he has and if it's under 50 it would say"

Sorry not Enough

and I want the program to end there.

Here is the code I have written:

cin >> money;
if (money <= 50) {
    cout << "Sorry not enough" << endl;
}
cout << "Here are the items you can buy" << endl;
int a = 50;
int b = 200;

of course this is not the entire code I wrote. If the person wrote a number less than 50, how do I make the code stop?

Thanks!

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
Miguel Nunez
  • 79
  • 1
  • 11

4 Answers4

1

You have to write return after:

cout << "Sorry not enough" << endl; 

This will stop the code.

ani627
  • 5,578
  • 8
  • 39
  • 45
Szymon
  • 88
  • 1
  • 2
  • 4
1

Your program ends when you return from main(), so you should arrange for that to happen.

Alternatively you could call exit(), but that's a bad idea since destructors won't run.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
1

You can write your code like this:

cin >> money;
if (money <= 50) {
    cout << "Sorry not enough" << endl;
}
else {
   cout << "Here are the items you can buy" << endl;
   // Operations you want to perform 
}
ani627
  • 5,578
  • 8
  • 39
  • 45
1

Using a return statement or the exit() function in C++ will exit the program. Your code would look like:

int main()
{
cin >> money;
if (money <= 50) {
    cout << "Sorry not enough" << endl;
    return 0;
}
cout << "Here are the items you can buy" << endl;
int a = 50;
int b = 200;
}

Conversely, with exit() function, it would look like:

#include<stdlib.h> //For exit function
int main()
{
cin >> money;
if (money <= 50) {
    cout << "Sorry not enough" << endl;
    exit(0);
}
cout << "Here are the items you can buy" << endl;
int a = 50;
int b = 200;
}
Vaibhav Bajaj
  • 1,934
  • 16
  • 29