我有一個包含 IP 地址的文本檔案。例如,我使用了矢量,但我很困惑,我不能。我試過 for 回圈,但它不起作用,因為我在第一個時使用。
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;
}
uj5u.com熱心網友回復:
您可以使用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;
}
可以在此處執行和檢查程式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/360993.html
上一篇:使用卡片區域下載BLOB檔案-OracleApexv21.1
下一篇:檢查檔案是否存在
