Question

I am using an if statement to get the users input with a bool value, if they enter 1 then the program continues to execute, if they enter 0 then I want the program to stop running completely. This is the code im using.

bool subscription;
cout << "Would you like to purchase a subscription to our newspaper?\n";
cout << "Enter 1 if yes, and 0 if no. ";
cin >> subscription;

if(subscription == false)
{
   cout << "We're sorry you don't want our services.";
   //this is where i want the program to stop, after it outputs that line.
}
else if(subscription == true)
{
    cout << "\nPlease enter your first and last name. ";
}

I have tried using return 0; after the cout statement, but that didn't work, it would just output the statement and then continue on with the program.

I also tried exit(); and that did the exact same thing.

No correct solution

OTHER TIPS

The problem is that instead of the comparison operator you are using the assignment operator

if(subscription = false)
{
cout << "We're sorry you don't want our services.";
//this is where i want the program to stop, after it outputs that line.
}
else if(subscription = true)
{
cout << "\nPlease enter your first and last name. ";
}

In thsi expression of the if statement

if(subscription = false)

you assigned false to subscription and the expression is also equal to false. As the result the compound statement of this if statement is not executed.

Change the code as

if(subscription == false)
{
cout << "We're sorry you don't want our services.";
//this is where i want the program to stop, after it outputs that line.
}
else if(subscription == true)
{
cout << "\nPlease enter your first and last name. ";
}

It would be even better if you would write

if( subscription )
{
    cout << "\nPlease enter your first and last name. ";
}
else 
{
    cout << "We're sorry you don't want our services.";
    // here you can place the return statement
}
#include <iostream>
using namespace std;

int main()
{
    bool subscription;
    cout << "Would you like to purchase a subscription to our newspaper?"<<endl;
    cout << "Enter 1 if yes, and 0 if no. "<<endl;
    cin >> subscription;
    if(!subscription){
        cout << "We're sorry you don't want our services."<<endl;
        //this is where i want the program to stop, after it outputs that line.
        return -1;
    }
    else{
        cout << "\nPlease enter your first and last name. "<<endl;
        return 0;
    }
}

A couple of guidelines:

  1. Do not use var = true or var = false (use double == for comparison)
  2. Do not user boolean variables var == true in comparisons with true or false, just use them directly as boolean conditions
  3. Put "<<"endl" when using streams for line breaks better than \n
  4. Use return in main function will return in that place, thus finishing your program.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top