C++查找方法不起作用

-3 c++ string methods find

我对c ++很陌生,所以我对缺乏知识感到抱歉,但是出于某种原因,我的find方法不起作用.任何帮助都会很棒,这是我正在使用的代码.

www.pastie.org/9434690

//String s21 
string s21 ="| o |";  

if(s21.find("1")){
    cout << "IT WORKS OMG " << s21 << endl;
}
else if(!s21.find("1")){
    cout << "HASOSDKHFSIF" << endl;
}
Run Code Online (Sandbox Code Playgroud)

谢谢

忘记提及,代码总是打印"IT WORKS",即使字符串中没有"o".

Rai*_*con 6

这里的问题是你的if语句.s21.find("1")将返回要匹配的字符串的字符串中第一个匹配项的索引.如果找不到匹配,则返回string::npos该值的枚举-1.如果语句将在所有不等于零的数字上返回true.所以你需要string::npos像这样测试它:

if(s21.find("1") != std::string::npos)
{
    cout << "IT WORKS OMG " << s21 << endl;
}
else
{
    cout << "HASOSDKHFSIF" << endl;
}
Run Code Online (Sandbox Code Playgroud)