Problem:
Modify the vowel statistics program to make it count the number of spaces, tabs, and line breaks that are read in
Code:
#include <iostream>using namespace Std;int main () {char ch;string str;int acnt = 0, ecnt = 0, icnt = 0, ocnt = 0, UCn t = 0, spacecnt = 0;int brcnt = 0, tabcnt = 0;while (cin.get (CH)) {switch (ch) {case ' a ': Case ' a ': Acnt++;break;case ' e ': case ' E ': ecnt++;break;case ' i ': Case ' I ': Icnt++;break;case ' o ': Case ' o ': Ocnt++;break;case ' u ': Case ' u ': Ucnt++;break;case ' : Spacecnt++;break;case ' \ n ': brcnt++;break;case ' \ t ': tabcnt++;break;default:break;}} cout<<acnt<< "<<eCnt<<" "<<iCnt<<" "<<oCnt<<" <<uCnt< <endl;cout<<brCnt<< "<<tabCnt<<" "<<spacecnt<<endl;return 0;}
Summarize:
(1) The >> input operator of CIN treats null characters (spaces, tabs, and carriage returns) as the end of the input, so special characters such as spaces, carriage returns, and tab are obtained using the Cin.get (ch) method.
(2) The case label in the switch statement must be an integer constant expression, and each case statement uses a break to jump out of the loop.
(3) Strstr () searches for the first occurrence of a string in another string. When the searched string is found, the function returns the address of the first matching string, or null if the searched string is not found.
C + + Primer (fourth edition) after class exercise 6.8