0

Can you explain me, why does it always output true? I would like to know if appointed substring is present in original string.

//c++ #include <iostream> #include<string> using namespace std; bool is_found(const string str){ if(str.find("am")) return true; else return false; } int main() { string a("12:45:56 pm"); cout << is_found(a); return 0; }

13th Sep 2021, 5:07 AM
TeaserCode
1 ответ
+ 5
The find() method returns the index of the substring's first character if found, or a special constant "npos" otherwise. See: https://en.cppreference.com/w/cpp/string/basic_string/find That constant is defined as: static const size_type npos = -1; Converted to a bool, that value is still true, hence your incorrect results. The correct condition would be: if ( str.find( "am" ) != string::npos ) ... Or, when shortening the function: return ( str.find( "am" ) != string::npos );
13th Sep 2021, 6:06 AM
Shadow
Shadow - avatar