计算两个字符序列

Counting two character sequence

本文关键字:字符 两个 计算      更新时间:2023-10-16

我也是新手C++但有其他语言的经验。

我正在通过:

书籍:C++入门第5版
练习5.12

在使用开关结构计算元音、空格和制表符的同时,练习还要求跟踪两个字符序列ffflfi在一些输入的文本中出现的次数。我已经看到了这个问题的其他解决方案,大多数使用布尔标志类型结构,但我选择使用字符串迭代器来跟踪。然而,作为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


同样好的做法是为每个charstring或其他任何东西使用计数器的instadmap

std::map<char,unsigned> charCounter;
charCounter['a']++;

而不是10printf()

for(auto const & c : charCounter)
{
for(auto const & i : charCounter.second)
{
cout << "The number of " << c << " vowels is: t" << i << endl;
}
}