【问题标题】:the no option in my if-else statement isnt working correctly [closed]我的 if-else 语句中的 no 选项无法正常工作 [关闭]
【发布时间】:2014-12-27 16:57:33
【问题描述】:

我编写此代码以使用 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;
}        

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

“很好,将继续提问。”

没关系。

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

【问题讨论】:

  • 如果此代码没有至少两次警告,请配置您的编译器以更好地帮助您。
  • 那甚至不应该编译,除非你在else (answer == no)cout之间还有一个额外的;

标签: c++ if-statement output


【解决方案1】:

我在这里看到两个不同的问题:第一个是您将字符串与布尔值进行比较,第二个是您没有初始化布尔变量。 我建议您更改 if(answer=="yes") 中的 if 语句 和if(answer=="no") 但我不明白这是否是你想要做的。

编辑:阅读 cmets 我明白了 OP 的含义。当然answer 应该是std::string 类型。

【讨论】:

  • 他在哪里比较字符串和布尔值?他宣布bool answer
  • 你是对的。我对 cin stataments 感到困惑
  • @Barmar 无论如何,这个答案指出了更好的方向,并涵盖了 OP 对布尔变量与字符串变量输入的混淆!
【解决方案2】:

您没有在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 &gt;&gt; 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;
}

【讨论】:

  • 好的,我会改正,看看是否有效,谢谢
  • 我试过了,但也没有用:cout>回答; {布尔是=真;布尔号=假; if(answer==yes) { cout
  • 你输入的是0还是1
  • @Barmar 正如我从原始帖子中读到的,我怀疑他们输入的是yesno。所有yes/no 布尔变量的东西都没什么用!
  • @πάνταῥεῖ 我知道,但我在回答中解释说那行不通。我在问他在执行我的更正时是否解决了这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-03
  • 2016-06-18
  • 1970-01-01
  • 2014-09-27
  • 1970-01-01
  • 2020-01-07
相关资源
最近更新 更多