c++经典题----统计一个文件“is”单词的个数


main.cpp

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
	fstream in;//文件读入流
	in.open("k:\\file1.txt", ios::in | ios::_Nocreate);//以读入不创建模式打开,即如果不存在则打开失败
	if (!in)
	{
		cout << "打开失败" << endl;
		return -1;
	}
	char ch1 = 0, ch2 = 0;//前一个字符,后一个字符
	unsigned int number = 0;//is的个数
	while (in.get(ch2))
	{
		if (ch1 == 'i'&&ch2 == 's')//如果前一个字符为i,后一个字符为s
		{
			number++;
		}
		ch1 = ch2;//后一个传到前一个
	}
	cout << number << endl;

	in.close();
	system("pause");
	return 0;
}

file1.txt

is that ture?
ok,that is ture
so what?
ok,ok.that i                   //此处的is中间夹了一个换行,所以不算一个is单词
s so bad.

运行结果:



猜你喜欢

转载自blog.csdn.net/tobe_numberone/article/details/78158803