formula is a string here.
find() is a member function of the string class, and so
formula.find( "OH " )
will return the index of the first occurrence of "OH" (i.e. position of letter O here) if "OH" is in the formula. If it isn't found, it will return a characteristic number (which may differ from system to system) but which can always be found as string::npos. Thus
formula.find( "OH" ) != string::npos
will be true if it does genuinely find a hydroxyl group in the formula.
The second part of your issue is the "ternary operator" (google it) which boils down to
result = test ? outcome_if_test_is_true : outcome_if_test_is_false
and it is always shorthand for an if...else block. The first code is equivalent to the longer form
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
#include <iostream>
#include <string>
using namespace std;
int main()
{
string formula;
cout << "Enter a molecular formula: ";
cin >> formula;
if ( formula.find( "OH" ) != string::npos ) // if the result of .find() was not equal to the not-found sentinel (string::npos)
{
cout << "This contains a hydroxyl group\n";
}
else
{
cout << "This does not contain a hydroxyl group\n";
}
}
|
Your code is a bit obscure, I'm afraid: you would find it much easier to use a std::string than a character array. Testing for eof is highly unreliable as well.
I'll post this, but I can see that I'm such a slow typist that I've been beaten to it!