c++ - 如何在 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;
}
解决方案
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;
}
程序可以在这里执行和检查。
推荐阅读
- docker - 使用 docker compose 在后台运行 ubuntu 容器
- c# - 将项目从现有 VisualStudioWorkspace 复制到新的 AdhocWorkspace
- python - 避免空值检查的架构解决方案
- java - 在条件生成器中按子句顺序添加正则表达式
- apache-kafka - Apache nifi 作为 cosumer 接收来自 kafka 主题的消息
- cron - 将 Quartz 调度程序转换为 unix cron 调度程序
- selenium-webdriver - 在 iOS 应用程序自动化时处理 iOS 应用程序中的日期选择器时面临的问题
- asp.net-mvc - 如何使用强类型视图处理 Asp.NET MVC 中的不同帖子源
- c# - 如何获取我在 SQL Server 中拥有的所有弹性池的名称?
- r - k-means 分析:如何将数据转换为数值?