我也是新的C++,但有其他語言的經驗。計數兩個字符序列
我工作過:
書: C++入門第五版。
練習: 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;
}
我認爲這屬於上[codereview.se。 –
我可能會使用'std :: map'來計算出現次數,以避免大量奇怪命名的變量 –
user463035818
雖然沒有錯,但我建議在'while'循環中添加'{}'。這是有效的,因爲它只是一個陳述,但它可能導致混亂,因爲'for'循環裏面有多少行。 –