简体   繁体   English

即使输入正确,我的其他提示也会显示

[英]My Else cout displays even if input is correct

Even i type Pythagoras or Probability it still displays my else output "topic not supported" how do i fix this? 即使我输入毕达哥拉斯或概率,它仍会显示其他输出“主题不受支持”,我该如何解决?

search = "Pythagoras";
pos = sentence.find(search);
if (pos != string::npos)                        
    cout << "pythagoras entry" << endl;
search = "Probability";
pos = sentence.find(search);
if (pos != string::npos)
    cout << "probability entry" << endl; 
else
    cout << "topic not supported" << endl;

If your sentence contains "Pythagoras", it will pass through the first if (outputting what's there), and then go on the "else" check for "Probability" - you don't break the execution after you found "Pythagoras" in the sentence, it will go for the second if , outputting what's in the "topic not found", because "Probability" != "Pythagoras". 如果您的句子包含“毕达哥拉斯”,它将通过第一个if (输出那里的内容),然后在“ else”中进行“概率”检查-在“毕达哥拉斯”中找到“毕达哥拉斯”后,您不会中断执行句子, 如果输出“找不到主题”中的内容,它将继续第二次,因为“概率”!=“毕达哥拉斯”。 If you put "Probability" in the sentence, "topic not found" should NOT be outputted, unless you didn't show us the code you're actually using. 如果在句子中添加“概率”,则除非您没有向我们显示您实际使用的代码,否则不应输出“找不到主题”。

To fix this, I suggest using a boolean flag, something like 为了解决这个问题,我建议使用布尔值标志,例如

bool flag = false;
search = "Pythagoras";
pos = sentence.find(search);
if (pos != string::npos)                    
{
    cout << "pythagoras" << endl;
    flag = true;
}
search = "Probability";
pos = sentence.find(search);
if (pos != string::npos)
{                    
    cout << "probability" << endl; 
    flag = true;
}

if (!flag)
    cout << "not supported" << endl;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM