Home > OS >  How to get same lines in c
How to get same lines in c

Time:11-15

I have a text file with IP addresses in it. For example, I used vector but I confused, i can't. I tried for loop but it was not work because of i am used while in first.
192.168.4.163
192.168.4.163
192.168.4.163
192.168.6.163
192.168.6.163

In output I would like to write
192.168.4.163 => 3 times 192.168.6.163 => 2 times

How can I do that?

#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;
}

CodePudding user response:

You can simplify your program by using std::map as shown below:

#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;
}

The program can be executed and checked here.

  • Related