2017-02-17 47 views
-3

我的程序检查输入字符串是否包含元音。如果未找到元音,则打印“找不到”。查找元音字符串不工作

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"; 
} 

无论输入的,每次我运行程序,它打印“找不到”。

+8

你必须做的=每个.find致电 –

+0

提示:看'的std :: string :: find'的返回值。我建议你看看'std :: string :: find_first_of'。 –

+1

'find'返回字符的位置,而不是'true'或'false'。如果未找到该值,它将返回'npos'。 –

回答

1

这是因为string::find不返回bool。它返回一个迭代器找到的元素。如果找不到该元素,则返回string::npos。这样做的适当方法是检查函数是否返回了其他值不是string::npos

看看这个例子:

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."; 

如果你理解上面的例子,我敢肯定,你将能够编辑您的代码,并得到预期的结果。

编辑:如Tobi303提到,问题在于只有一个!= string::npos的实例。创建逻辑语句something || something || something您希望somethingbool。在这种情况下,您应该比较EACHstring::find的实例与string::npos。这将是这样的:

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} 
+0

他有'!= sting :: npos',但只有一次。 – user463035818

+1

似乎像OP知道'find'返回什么,但不知道如何或几个条件 – user463035818

+0

@ tobi303,我编辑了答案提及您的输入。我原本以为OP期待'string :: find'的'bool'返回值。良好的捕获 – Fureeish