首页 > 解决方案 > 如何在 C++ 中获得相同的行

问题描述

我有一个包含 IP 地址的文本文件。例如,我使用了矢量,但我很困惑,我不能。我尝试了 for 循环,但它不起作用,因为我首先使用了 while。
192.168.4.163
192.168.4.163
192.168.4.163
192.168.6.163
192.168.6.163

在输出中我想写
192.168.4.163 => 3 times 192.168.6.163 => 2 times

我怎样才能做到这一点?

#include<stdlib.h>
#include<iostream>
#include<cstring>
#include<fstream>
#include <algorithm>
#include <vector>

using namespace std;

int main()
{
    ifstream listfile;
    listfile.open("log.txt");
    ofstream codefile;
    codefile.open("Code.txt");
    
    ifstream readIp;
    string ipLine;
    readIp.open("Code.txt");
    
    string temp;
    while(listfile>>temp) //get just ips
    {
        codefile<<temp<<endl;
        listfile>>temp;
        getline(listfile, temp);
    }

    listfile.close(); //closed list 
    codefile.close(); //closed just ip list file
    vector <string> currentSet;
    while(getline(readIp, ipLine))
    {
        ipLine.erase(std::remove(ipLine.begin(), ipLine.end(), '"'), ipLine.end()); //removed " 
        currentSet.push_back(ipLine);

        cout << ipLine + " Number of logged on : x" << endl;
    }
    
    readIp.close();
    return 0;
}

标签: c++file

解决方案


std::map您可以通过使用如下所示来简化您的程序:

#include <iostream>
#include <map>
#include <sstream>
#include <fstream>
int main() {
    
    //this map maps each word in the file to their respective count
    std::map<std::string, int> stringCount;
    std::string word, line;
    int count = 0;//this count the total number of words
    
    std::ifstream inputFile("log.txt");
    if(inputFile)
    {
        while(std::getline(inputFile, line))//go line by line
        {
            std::istringstream ss(line);
            
            //increment the count 
            stringCount[line]++;
            
        }
    }
    else 
    {
        std::cout<<"File cannot be opened"<<std::endl;
    }
    
    inputFile.close();
    
    std::cout<<"Total number of unique ip's are:"<<stringCount.size()<<std::endl;
    //lets create a output file and write into it the unique ips 
    std::ofstream outputFile("code.txt");
    
    
    for(std::pair<std::string, int> pairElement: stringCount)
    {
        std::cout<<pairElement.first<<" => "<<pairElement.second<<" times "<<std::endl;
        outputFile<<pairElement.first<<" => "<<pairElement.second<<" times \n";
      
    }
    outputFile.close();
    return 0;
}

程序可以在这里执行和检查。


推荐阅读