我正在使用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();
,并且做了完全相同的事情。
答案 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;
}
}
一些指导原则: