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

why code is printing all the first index?

本文关键字:第一个 索引 代码 打印 为什么      更新时间:2023-10-16

我试图编写一个程序,将单词从文本文件转换为猪拉丁语。 我得到了分隔文本文件单词的代码,但现在我在尝试整理它们时遇到了麻烦。 当我运行此代码时,它总是打印所有单词的第一个索引,而不是与 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;
    }
}
if (word[0] == 'a'||'e'||'i'||'o'||'u'||'A'||'E'||'I'||'O'||'U')
这不是

||在C++的工作方式。但这并不意味着上述内容会导致编译错误。不,从编译器的角度来看,这是正确的;它唯一的问题是它没有做你想做的事情!相反,条件将始终true 。这就是为什么它会打印代码中所有单词的第一个字符。

要得到你想要的,你必须||写成:

if (word[0] == 'a'|| word[0] == 'e'|| word[0] ==  'i' || ... so on)

也就是说,您必须分别比较每个字符。这肯定是令人恼火的。


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

或者,您可以将std::find用作:

//C++03 and C++11 both
if ( std::find(v.begin(), v.end(), word[0]) != v.end() )

它比前一个短了一点。此外,这也将在 C++03 中工作!


或者,您可以将std::count用作:

//C++03 and C++11 both
if ( std::count(v.begin(), v.end(), word[0]) ) 

甚至更短。


或者,您可以将std::string::find用作:

//C++03 and C++11 both
if ( v.find(word[0]) != std::string::npos)

哪个最短!


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

  • std::any_of
  • std::find
  • std::count
  • std::string::find

希望有帮助。

上面关于使用大量word[0] == 'a' || word[0] == 'e' || ...的建议是正确的解决方案,可以"修复"您编写的内容,使其能够完成您对单个 if 语句的期望。

你可以这样做:

 switch(word[0])
 {
    case 'a':
    case 'e':
    case 'i':
    ... /// you'll have to fill the rest in yourself. 
        cout << word[0]; 
        break; 
 } 

或者你可以使用老式的C风格strchr

if (strchr("aeiouAEIOU", word[0]) != NULL)
{
    cout << word[0];
}

可能还有其他六种解决方案。这完全取决于您喜欢哪种"风格"。我可能会选择开关作为我的首选。

相关文章: