簡體   English   中英

即使輸入正確,我的其他提示也會顯示

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

即使我輸入畢達哥拉斯或概率,它仍會顯示其他輸出“主題不受支持”,我該如何解決?

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 (輸出那里的內容),然后在“ else”中進行“概率”檢查-在“畢達哥拉斯”中找到“畢達哥拉斯”后,您不會中斷執行句子, 如果輸出“找不到主題”中的內容,它將繼續第二次,因為“概率”!=“畢達哥拉斯”。 如果在句子中添加“概率”,則除非您沒有向我們顯示您實際使用的代碼,否則不應輸出“找不到主題”。

為了解決這個問題,我建議使用布爾值標志,例如

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