计算两个字符序列
Counting two character sequence
我也是新手C++但有其他语言的经验。
我正在通过:
书籍:C++入门第5版
练习:5.12
在使用开关结构计算元音、空格和制表符的同时,练习还要求跟踪两个字符序列ff
、fl
和fi
在一些输入的文本中出现的次数。我已经看到了这个问题的其他解决方案,大多数使用布尔标志类型结构,但我选择使用字符串迭代器来跟踪。然而,作为C++新手,我不确定我的代码是否有任何固有的危险(即指向无效对象的迭代器(。这段代码看起来没问题吗?
#include <iostream>
#include <string>
using std::string;
using std::cin;
using std::cout;
using std::endl;
int main()
{
string text;
unsigned aCnt = 0, eCnt = 0, iCnt = 0, oCnt = 0, uCnt = 0, spaceCnt = 0, nlCnt = 0, tabCnt = 0, ffCnt = 0, flCnt = 0, fiCnt = 0;
bool flag = false;
while (getline(cin, text))
for (auto it = text.begin(); it != text.end(); ++it) {
*it = tolower(*it);
switch (*it) {
case 'a' :
++aCnt;
break;
case 'e' :
++eCnt;
break;
case 'i':
if (it != text.begin())
if (*(it - 1) == 'f')
++fiCnt;
else
++iCnt;
break;
case 'o' :
++oCnt;
break;
case 'u' :
++uCnt;
break;
case ' ':
++spaceCnt;
break;
case 'n':
++nlCnt;
break;
case 't':
++tabCnt;
break;
case 'f' :
//Control strucutre that checks if the character pointed to previously was an f.
if (it != text.begin())
if (*(it - 1) == 'f')
++ffCnt;
break;
case 'l':
if (it != text.begin())
if (*(it - 1) == 'f')
++flCnt;
break;
}
}
cout << "The number of 'a' vowels is: t" << aCnt << endl;
cout << "The number of 'e' vowels is: t" << eCnt << endl;
cout << "The number of 'i' vowels is: t" << iCnt << endl;
cout << "The number of 'o' vowels is: t" << oCnt << endl;
cout << "The number of 'u' vowels is: t" << uCnt << endl;
cout << "The number of tabs read is: t" << tabCnt << endl;
cout << "The number of newlines is: t" << nlCnt << endl;
cout << "The number of spaces read is: t" << spaceCnt << endl;
cout << "The number of 'ff' read is: t" << ffCnt << endl;
cout << "The number of 'fl' read is: t" << flCnt << endl;
cout << "The number of 'fi' read is: t" << fiCnt << endl;
return 0;
}
*it = tolower(*it);
正在就地修改字符串。我不认为这是您想要做的,因为通常计数会假设未修改的传入序列。我建议你使用const_iterator
来防止自己遇到这些问题。
如果您需要在进行过程中修改容器、多次访问元素或以其他方式以非线性方式遍历容器,则应使用普通的for
循环或其表亲之一。
基于范围的for
适用于需要访问容器的每个元素一次的情况。当您多次访问某些元素时,这可能会导致问题。
您应该按照@SergeyA提到的使用const_iterator
。 而不是修改*it
做
switch (tolower(*it))
或者将其存储到变量temp
。
同样好的做法是为每个char
或string
或其他任何东西使用计数器的instadmap
。
std::map<char,unsigned> charCounter;
charCounter['a']++;
而不是10
printf()
的
for(auto const & c : charCounter)
{
for(auto const & i : charCounter.second)
{
cout << "The number of " << c << " vowels is: t" << i << endl;
}
}
相关文章:
- 查找字符在两个索引之间出现的次数
- 如何读取单个字符并在输入两个字符序列时输出? 使用 while 循环和C++
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- 函数返回两个字符串的第一个常用字符
- 在函数中连接两个字符,并在 C++ 中返回输出
- 为什么要更改这两个代码的输出"&"字符?
- 舍入 QDecDouble 值,精度最多为两个字符
- 计算两个字符序列
- 在c++中连接两个字符
- 查找和比较两个字符串中的字符
- 为什么C++中不允许连接两个常量字符*?
- 如何使用排序和比较这两个函数在 c++ 中对字符数组进行排序?
- 有没有办法我可以从 istringstream 中读取两个字符
- 如何查找两个字符串 c++ 中常用字符的数量
- 如何查看两个字符变量是否相等
- 使用位于 C 字符串中的两个字符*获取子字符串
- C++ std::string 中是否有任何函数可以计算两个字符串的相同起始字符的总数或任何最佳方法
- 重命名两个目录中的文件名,如果它们之间的某些字符匹配 - 矢量下标超出范围
- 比较两个字符的问题
- 如何修复密码条目,它一次输入两个字符