ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

c++统计文件中出现某位数的个数

2026/9/21 15:05:53 拓冰建站 浏览量
c++统计文件中出现某位数的个数
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<fstream>
#include<string>#define NUM 33
#define NUM2 7using namespace std;//统计次数
bool ststistics(const char* path, int ball_16[NUM]) {int result[NUM];ifstream file;//读取文件int i = 0;//判断文件路径是否为空if (!path) {cerr << "path is NULL" << endl;return false;}//打开文件file.open(path);if (file.fail()){cerr << "打开输入文件出错" << strerror(errno) << endl;return false;}//读取文件到数组,一行读7个do {int i = 0;for (i = 0; i < NUM2; i++){file >> result[i];if (file.eof())//检查文件是否已经到达了结尾(EOF){break;}}/*if (file.fail()){cerr << "读取文件出错" << strerror(errno) << endl;return false;}*/if (i == 0) { break; }if (i < NUM2) {cerr << "只读到" << i << "行数据" << endl;file.close();return false;}//输出数组for (i = 0; i < NUM2; i++){cout << " " << result[i];}cout << endl;//对读入的数据进行统计for (i = 0; i < NUM2; i++){int index = *(result + i) - 1;//1球>>0if (index >= 0 && index < 33){*(ball_16 + index) += 1;}}} while (1);file.close();return true;}int main()
{string filename;int ball_16[NUM] = { 0 };cout << "请输入文件名" << endl;cin >> filename;if (ststistics(filename.c_str(), ball_16))//文件类型转化.c_str{for (int i = 0; i < NUM; i++){cout << "第" << i + 1 << "号球出现:" << ball_16[i] << endl;}}else {//统计失败cerr << "统计出错" << endl;}}