-3

My program checks if an input string contains vowels. In case no vowels were found, it prints "not found".

string stringInput;
cout << "Enter a sentence: ";
cin >> stringInput;
if ((stringInput.find('a')) || (stringInput.find('e')) || (stringInput.find('i')) || 
    (stringInput.find('o')) || (stringInput.find('u')) != string::npos)
{
    cout << "not found";
}
else
{
    cout << "found";
}

Regardless of the input, everytime I run the program, it prints "not found".

Pierre Arlaud
  • 4,040
  • 3
  • 28
  • 42

1 Answers1

1

That's because string::find does not return bool. It returns an iterator the the found element. If the element was not found, it returns string::npos. The appropriate way of doing this is checking whether the function returned something else than string::npos.

Take a look at this example:

std::string Name = "something";
if(Name.find('g') != std::string::npos) std::cout << "Found the letter 'g'!";
else std::cout << "There is no letter 'g' in the string Name.";

If you understand the example above, I'm sure you will be able to edit your code and get the expected result.

EDIT: as Tobi303 mentioned, the problem lies with only one instance of != string::npos. Creating logical statements are something || something || something you expect something to be a bool. In this case, you should compare EACH instance of string::find with string::npos. That would look like this:

if((stringInput.find('a')) != std::string::npos || (stringInput.find('e')) != std::string::npos || (stringInput.find('i')) != std::string::npos || (stringInput.find('o')) != std::string::npos || (stringInput.find('u')) != string::npos){//code}
Fureeish
  • 12,533
  • 4
  • 32
  • 62