| 循环读取文件第一列数据是一个五位数,判断这个五位数的前四个数字是否相同,相同的为一组数据,并统计数量,统计完成后这一组相同数据中最大的五位数进行输出,重复数量也进行输出。读取目录:G:\Users\Administrator\Desktop\C 
 (这里我要求,一次没重复的珍兽ID也要输出,输出显示为1变)
 
 #include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <algorithm>
using namespace std;
int main()
{
    // 打开文件
    ifstream input("G:\\Users\\Administrator\\Desktop\\C\\input.txt");
    if (!input.is_open()) {
        cerr << "Failed to open file." << endl;
        return 1;
    }
    // 定义map容器,key为前四个数字相同的五位数,value为pair,其中first表示重复数量,second为最大的五位数
    map<string, pair<int, string>> data_map;
    // 循环读取文件,按行处理
    string line;
    while (getline(input, line)) {
        // 利用tab分割符分割每行数据
        size_t pos = line.find('\t');
        if (pos == string::npos) {
            cerr << "Invalid input format." << endl;
            return 1;
        }
        string col1 = line.substr(0, pos);  // 第一列数据
        string col2 = line.substr(pos + 1);  // 第二列数据
        // 判断第一列数据是否合法
        if (col1.length() != 5) {
            cerr << "Invalid input format." << endl;
            return 1;
        }
        for (char c : col1) {
            if (!isdigit(c)) {
                cerr << "Invalid input format." << endl;
                return 1;
            }
        }
        // 判断前四个数字是否相同,相同则为同一组数据
        string key = col1.substr(0, 4);
        auto iter = data_map.find(key);
        if (iter != data_map.end()) {
            // 如果已存在该组数据,则更新pair的值
            iter->second.first++;  // 重复数量加1
            iter->second.second = max(iter->second.second, col1);  // 更新最大的五位数
        } else {
            // 如果不存在该组数据,则添加该组数据
            data_map.emplace(key, make_pair(1, col1));  // 重复数量为1,最大的五位数为当前读入的五位数
        }
    }
    // 关闭文件
    input.close();
    // 打开输出文件
    ofstream output("G:\\Users\\Administrator\\Desktop\\C\\output.txt");
    if (!output.is_open()) {
        cerr << "Failed to open output file." << endl;
        return 1;
    }
    // 遍历map容器,输出结果
    for (auto& pair : data_map) {
        if (pair.second.first >= 3) {  // 如果重复数量大于等于3,则减少2
            pair.second.first -= 2;
        }
        // 输出结果到文件,格式为:前四个数字相同的五位数\t重复数量\t最大的五位数
        output << pair.first << '\t' << pair.second.first << '\t' << pair.second.second << endl;
    }
    // 关闭输出文件
    output.close();
    return 0;
}
 
   
 |