Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/147.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ if-else语句中的no选项工作不正常_C++_If Statement_Output - Fatal编程技术网

C++ if-else语句中的no选项工作不正常

C++ if-else语句中的no选项工作不正常,c++,if-statement,output,C++,If Statement,Output,我写这段代码是为了使用if-else语句,但是“no”输出与yes相同,我首先尝试在本地声明yes和no变量,这修复了我得到的第一个错误。但现在他们无法区分输出。无论输入是什么,输出是和否的条件 代码如下: #include<iostream> #include<string> using namespace std; int main() { string name; bool answer; cout<<"Welcome user

我写这段代码是为了使用if-else语句,但是“no”输出与yes相同,我首先尝试在本地声明yes和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;
}        
#包括
#包括
使用名称空间std;
int main()
{
字符串名;
布尔回答;

cout您不需要在
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 :-)";
}
bool yes = true;
bool no = 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;
}
但是这些都是非常无用的。你不需要将布尔值与任何东西进行比较,你可以直接在以下条件下使用它们:

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 :-)";
}

我在这里看到两个不同的问题:第一个是比较字符串和布尔值,第二个是没有初始化布尔值变量。 我建议您更改
if(答案==“yes”)
if(答案==“否”)
但我不明白你是不是想这么做


编辑:阅读评论,我明白了OP的意思。当然
答案
应该是
std::string
类型。

如果你没有得到至少两个关于此代码的警告,请配置你的编译器以更好地帮助你。这甚至不应该编译,除非你在
之间还有一个额外的
(答案==否)
cout
。好的,我会进行更正,看看它是否有效,谢谢。我尝试了这个,但它也不起作用:你是否可以输入
0
1
?@Barmar正如我从原始帖子中读到的,我怀疑他们输入的是
。所有这些
/code>/no>可恶的东西是毫无用处的!@πάνταῥεῖ 我知道,但我在回答中解释了这不起作用。我在问他在实施我的更正时是否解决了这个问题。他在哪里比较字符串和布尔值?他声明
bool answer
。你是对的。我被cin弄糊涂了stataments@Barmar无论如何,这个答案指出了更好的方向,并涵盖了OP的合作关于布尔与字符串变量输入的融合!