【问题标题】:Stop a program from running in c++ if bool is false如果 bool 为 false,则停止程序在 C++ 中运行
【发布时间】:2014-03-13 01:26:06
【问题描述】:

我正在使用 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. ";
}

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

我也试过exit();,结果完全一样。

【问题讨论】:

  • if(subscription = false) - 你真的是说if(subscription == false) 吗?
  • 我会编译这将完整的警告,这些会告诉你问题
  • 是的,这就是我的意思,但我认为这不能解决问题。
  • 这段代码在主函数中吗?你试过 exit(0) 吗?你的意思是你的应用程序没有退出?
  • exit(0) 应该可以工作。如果你想要一个异常的进程终止你可以使用abort()这两个函数都在cstdlib

标签: c++ boolean return exit


【解决方案1】:

问题是您使用的是赋值运算符而不是比较运算符

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
}

【讨论】:

  • 这是正确的,但要让程序停在那里,我所要做的就是包含 return 0;修复 == 之后。
  • @Christoph 是的,你是对的。我在最后一个代码示例的注释中指出了它。
【解决方案2】:
#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. 不要使用布尔变量 var == true 与 true 或 false 进行比较,直接将它们用作布尔条件
  3. 在使用流进行换行时放置“
  4. 在 main 函数中使用 return 将返回该位置,从而完成您的程序。

【讨论】:

    最近更新 更多