pex2_12.cpp

来自「数据结构C++代码,经典代码,受益多多,希望大家多多支持」· C++ 代码 · 共 63 行

CPP
63
字号
#include <iostream.h>
#include <iomanip.h>
#include <fstream.h>
#include <stdlib.h>

void main(void)
{
	char fileName[50];
	ifstream fin;
	char c;
	int numPeriod = 0, numComma = 0, numExclam = 0, numQues = 0;
	
	cout << "Enter the file name: ";
	cin >> fileName;
	
	fin.open(fileName, ios::in | ios::nocreate);
	if (!fin)
	{
		cerr << fileName << " cannot be opened!" << endl;
		exit(1);
	}

	// read all characters one at a time, incrementing the appropriate
	// variable when we find one of the punctuation marks
	while(fin.get(c))
		switch(c)
		{
			case '.':
				numPeriod++;
				break;
			case ',':
				numComma++;
				break;
			case '!':
				numExclam++;
				break;
			case '?':
				numQues++;
				break;
		}

	cout << "Character    Number of Occurrences" << endl << endl;
	cout << ".  " << setw(20) << numPeriod << endl;
	cout << ",  " << setw(20) << numComma << endl;
	cout << "!  " << setw(20) << numExclam << endl;
	cout << "?  " << setw(20) << numQues << endl;
}

/*
<Run>

<file "charfile.dat">
Are 2 periods (.), 3 commas, 2 exclamation marks(!),
and 1 question mark? That is the case. (We hope!)

Enter the file name: charfile.dat
Character    Number of Occurrences

.                     2
,                     3
!                     2
?                     1
*/	

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?