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.

运行结果:



  • 2
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
```c #include <stdio.h> #include <string.h> int main() { char word[100]; // 定义一个长度为100的字符数组,用于存储单词 int count = 0; // 定义一个计数器,用于统计单词is的个数 FILE *fp; // 定义一个文件指针 fp = fopen("example.txt", "r"); // 打开名为example.txt的文本文件,使用只读模式 while (fscanf(fp, "%s", word) != EOF) { // 从文件中读取一个字符串,直到读取到文件结尾 if (strcmp(word, "is") == 0) { // 如果读取到的字符串是单词is count++; // 将计数器加1 } } printf("The number of 'is' in the file is %d\n", count); // 输出单词is的个数 fclose(fp); // 关闭文件指针 return 0; // 返回0,表示程序正常结束 } ``` 解释各个语句: 1. `#include <stdio.h>`:引入标准输入输出库的头文件。 2. `#include <string.h>`:引入字符串处理库的头文件。 3. `int main()`:主函数。 4. `char word[100];`:定义一个长度为100的字符数组word,用于存储单词。 5. `int count = 0;`:定义一个计数器count,用于统计单词is的个数。 6. `FILE *fp;`:定义一个文件指针fp。 7. `fp = fopen("example.txt", "r");`:打开名为example.txt的文本文件,使用只读模式,并将文件指针赋值给fp。 8. `while (fscanf(fp, "%s", word) != EOF)`:循环从文件中读取一个字符串,并判断字符串是否结束。 9. `if (strcmp(word, "is") == 0)`:如果读取到的字符串是单词is,则执行以下语句。 10. `count++;`:将计数器count加1。 11. `printf("The number of 'is' in the file is %d\n", count);`:输出单词is的个数。 12. `fclose(fp);`:关闭文件指针fp。 13. `return 0;`:返回0,表示程序正常结束。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值