如果bool为false,则停止在c ++中运行程序

时间:2014-02-13 22:08:29

标签: c++ boolean return exit

我正在使用if语句来获取bool值的用户输入,如果他们输入1然后程序继续执行,如果他们输入0然后我希望程序完全停止运行。这是我正在使用的代码。

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. ";
}

我尝试在return 0;语句之后使用cout,但这不起作用,它只会输出语句然后继续使用该程序。

我也尝试了exit();,并且做了完全相同的事情。

2 个答案:

答案 0 :(得分:3)

问题在于您使用赋值运算符

而不是比较运算符
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. ";
}

在if语句的表达中

if(subscription = false)

您为订阅分配了false,表达式也等于false。结果,不执行此if语句的复合语句。

将代码更改为

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. ";
}

如果你要写

会更好
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
}

答案 1 :(得分:0)

#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;
    }
}

一些指导原则:

  1. 不要使用var = true或var = false(使用double ==进行比较)
  2. 在与true或false的比较中不要使用布尔变量var == true,只需将它们直接用作布尔条件
  3. 在使用流优先于\ n
  4. 的流时放置“&lt;&lt;&lt;”endl“
  5. 使用主函数返回将返回该位置,从而完成程序。