2014-12-27 83 views
-5

我编写了此代码以使用if-else语句,但“no”输出与yes相同,我首先尝试在本地声明yes和no变量,这解决了我得到的第一个错误。但是现在他们无法区分产出。无论输入是什么,是和不输出的条件。我的if-else语句中的no选项无法正常工作

这里是下面的代码:

#include<iostream> 
#include<string> 
using namespace std; 
int main() 
{ 
    string name; 
    bool answer; 
    cout<<"Welcome user 'Divine 9'..."<<"What is your name?"<<endl; 
    getline(cin, name); 
    cout<<endl<<"Hello "<<name<<", my name is Xavier."<<endl<<" I am going to ask you some questions about yourself. Fear not, i will not take any of your information back to the boss man, or store it."<<endl; 
    cout<<"Is this okay with you? (yes/no)"<<endl; 
    cin>>answer; 
    { 
     bool yes; 
     bool no; 
     if(answer==yes) 
     cout<<"Great, will proceed with the questions!"<<endl; 
     else (answer==no) 
     cout<<"That is okay."; 
    } 
    return 0; 
}   

所以,如果我输入yes,它会输出:

“伟大的,将与问题继续进行。”

没关系。

如果我输入no,它会输出相同。 有人可以帮我解决这个问题吗?我以为我有它,但我想我不会

+2

如果您对此代码没有*至少*两个警告,请配置您的编译器以更好地帮助您。 – nvoigt 2014-12-27 17:05:29

+0

这应该不会编译,除非在else(answer == no)和'cout'之间还有一个额外的';'。 – 2014-12-27 17:06:07

回答

1

你没有把条件后else。你只是发表声明或阻止 - 条件只是以前的if失败。因此,它应该是:

if (answer == yes) { 
    cout<<"Great, will proceed with the questions!"<<endl; 
} else { 
    cout<<"That is okay, still love the Gamma Sig ladies, especially that_girl_teejay :-)"; 
} 

如果你想测试的另一个条件,您使用else if (condition)

另一个问题:您从未初始化yesno。它应该是:

bool yes = true; 
bool no = false; 

但是这些都是没用的。你不需要任何东西来比较布尔值,你可以在条件中直接使用它们:

if (answer) { 
    cout<<"Great, will proceed with the questions!"<<endl; 
} else { 
    cout<<"That is okay, still love the Gamma Sig ladies, especially that_girl_teejay :-)"; 
} 

注意,当你输入一个boolcin >> answer,你不能键入yesnobool只允许输入1(对于true)和0(对于false)。如果你想允许单词作为答案,你应该输入一个字符串并与字符串进行比较。它应该是:

string answer; 
... 
const string yes = "yes"; 
const string no = "no"; 
if (answer == yes) { 
    cout<<"Great, will proceed with the questions!"<<endl; 
} else if (answer == no) { 
    cout<<"That is okay."<<endl; 
} else { 
    count<<"Please enter yes or no."<<endl; 
} 
+0

好的将进行更正,看看它是否有效,谢谢 – antonio 2014-12-27 17:06:52

+0

我试过这个,但它也没有工作: cout <<“这对你好吗?(是/否) “<< ENDL; CIN >>答案; {布尔是= TRUE; 布尔无= FALSE; 如果(答案==是) { 的cout <<” 太好了,将与继续问题 “<< ENDL;} 其他 的cout <<”!这是正常情况,还是钟情于伽玛西格女士们,尤其是that_girl_teejay :-)“;} 返回0;} – antonio 2014-12-27 17:19:08

+0

你进入'0'或' 1'? – Barmar 2014-12-27 17:22:35

2

我在这里看到两个不同的问题:第一个是,你比较一个布尔值的字符串,第二个是,你是不是你的初始化布尔变量。 我建议你改变你在if(answer=="yes")if(answer=="no") 如果陈述但我不明白,如果这是你想要做的。

编辑:阅读评论我想出了OP的含义。当然answer应该是std::string类型。

+0

他在哪里比较字符串与布尔值?他宣布“布尔答案”。 – Barmar 2014-12-27 17:09:16

+0

你说得对。我被cin stataments所困惑 – BiA 2014-12-27 17:13:04

+0

@Barmar无论如何,这个答案指出了更好的方向,并且涵盖了OP关于布尔变量和字符串变量输入的混淆! – 2014-12-27 17:47:03