为什么代码打印所有第一个索引?

Bri*_*iem 0 c++ string file

我试图编写一个程序,将文本文件中的单词转换为猪拉丁语.我得到了代替文本文件的单词的代码,但我现在很困难,试图解决它们.当我运行此代码时,它始终打印所有单词的第一个索引,而不是与if语句匹配的单词

void wordpro(string sent)
{
  string word;

  istringstream iss(sent, istringstream::in);
  while (iss>> word)
  if (word[0] == 'a'||'e'||'i'||'o'||'u'||'A'||'E'||'I'||'O'||'U')
  {
    cout<< word[0] <<endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

Naw*_*waz 10

if (word[0] == 'a'||'e'||'i'||'o'||'u'||'A'||'E'||'I'||'O'||'U')
Run Code Online (Sandbox Code Playgroud)

这不是||C++的工作原理.但这并不意味着,上面会导致编译错误.不,从编译器的角度来看,这是正确的; 它唯一的问题是它没有按照你的意图去做!相反,条件永远是true.这就是为什么它打印代码中所有单词的第一个字符.

为了得到你想要的东西,你必须写成||:

if (word[0] == 'a'|| word[0] == 'e'|| word[0] ==  'i' || ... so on)
Run Code Online (Sandbox Code Playgroud)

也就是说,你必须分别比较每个角色.这肯定是恼人的.


C++ 11已经为您节省了时间,因此您可以使用std::any_of:

//C++11 only

std::string const v = "aeiouAEIOU";
if (std::any_of(v.begin(), v.end(), [](char c){ return word[0] == c;}) 
Run Code Online (Sandbox Code Playgroud)

或者您可以使用std::find:

//C++03 and C++11 both

if ( std::find(v.begin(), v.end(), word[0]) != v.end() )
Run Code Online (Sandbox Code Playgroud)

它比前一个短了一点.而且,这也适用于C++ 03!


或者您可以使用std::count:

//C++03 and C++11 both

if ( std::count(v.begin(), v.end(), word[0]) ) 
Run Code Online (Sandbox Code Playgroud)

甚至更短.


或者您可以使用std::string::find:

//C++03 and C++11 both

if ( v.find(word[0]) != std::string::npos)
Run Code Online (Sandbox Code Playgroud)

这是最短的!


阅读文档,了解它们各自的真​​正作用,以及为什么它适用于您的案例:

希望有所帮助.

  • @BrianChiem他刚给你看了一个更短的路. (2认同)