为什么代码打印所有第一个索引
why code is printing all the first index?
我试图编写一个程序,将单词从文本文件转换为猪拉丁语。 我得到了分隔文本文件单词的代码,但现在我在尝试整理它们时遇到了麻烦。 当我运行此代码时,它总是打印所有单词的第一个索引,而不是与 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];
}
可能还有其他六种解决方案。这完全取决于您喜欢哪种"风格"。我可能会选择开关作为我的首选。
相关文章:
- 为什么 Boost multi_index只修改第一个索引的键时对第二个索引进行比较?
- 一个 2D 数组,并按行存储值.第一个循环用于行索引,第二个循环用于列索引
- "如何使用C++将字符串的第一个和最后一个索引返回到向量中?
- 查找数组的第一个和最后一个索引,其中 from 和 to 元素的顺序总和最大
- 数组:如何在指定索引之前显示数组的第一个和最后一个元素以及数组元素的差异?
- 如何使用二叉搜索返回姓氏(给定字符串)的第一个索引/出现次数?
- 如何在 for 循环中解决潜在的 getline() 问题,数组的第一个索引没有显示?
- 如何在指针初始化为数组的第一个索引后释放指针
- 尝试将文件读入结构数组,但 for 循环仅显示第一个索引,其余索引显示为零
- 如何使用 Boost V2 1.70 日志记录库在第一个索引(例如 logtrail01.txt)保留最新的日志文件名?
- 如何在具有相同第一个索引 (c++) 的二维矩阵中添加值
- 在C 中返回向量中元素的第一个索引
- 在排序数组 X 中搜索第一个索引 i,使得 X[i] >= a
- 删除字符*[] 中的第一个索引
- 使用分而治之搜索字符串中'xy'的第一个索引
- 结构数组索引 在第一个索引之后未填充
- 在不使用图形的情况下,以最小的乘积从第一个索引到最后一个索引
- QDataWidgetMapper只更新第一个索引到QSqlRelationalTableModel
- 为什么代码打印所有第一个索引
- c++指针垃圾值只在第一个索引上