C++读取txt文件并统计数字范围个数

txt文件内容:有一万多个整型数字,每个字一行,如图2-记事本.    运行结果如下


代码如下:

// temp_project.cpp: 定义控制台应用程序的入口点。
//

/*
#include "stdafx.h"

int main()
{
printf("------------------");
return 0;
}


*/

//#include "stdafx.h"//我的vs2012编译器版本低,所以直接将此句注释掉了,仍可以运行出来
#include <math.h>
#include <string>
#include <fstream>
#include<iostream>
#include<cassert>
#define hh printf("\n===================================\n");

using std::string;
using namespace std;

int main()
{
	int count0_2_10 = 0;
	int count11_2_20 = 0;
	int count21_2_30 = 0;
	int count31_2_40 = 0;
	int count41_2_infinite = 0;
	string s = "D:\\2.txt";
	ifstream infile;
	infile.open(s.data());
	assert(infile.is_open());
	string a;
	int temp = 0;
	while (getline(infile,a))
	{
	//	cout << a << endl;
		for ( int i = 0; i < a.length(); i++)
		{
			temp *= 10;
			temp = temp+a.at(i) - 0x30;
		}
		if (temp>=0&&temp<=10)
		{
			count0_2_10++;
		}
		if (temp >=11 && temp <= 20)
		{
			count11_2_20++;
		}
		if (temp >= 21 && temp <= 30)
		{
			count21_2_30++;
		}
		if (temp >= 31 && temp <= 40)
		{
			count31_2_40++;
		}
		if (temp >= 41)
		{
			count41_2_infinite++;
		}
		temp = 0;
	}
	printf("0-10: %d\n  ", count0_2_10);
	printf("11-20: %d\n  ", count11_2_20);
	printf("21-30: %d\n  ", count21_2_30);
	printf("31-40: %d\n  ", count31_2_40);
	printf(">41: %d\n  ", count41_2_infinite);
	infile.close();
	 system("pause");
	return 1;
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值