C++ PROGRAM
1. Open the file input called "info.txt" read it and store the data in a vector.
2. Order the data by IP to perform the searches
3. Ask the user for the information search start and end IP's
- Example of data on the info text:
Jun 11 23:26:10 908.93.383.85:4940 Failed password for
admin
Aug 2 05:13:39 355.45.117.69:4551 Failed password for root
Oct 24 02:32:14 852.37.168.72:6796 Illegal user
4. Display the records corresponding to those IPs
5. Store the result of the sorting in a file called "sorted.txt"
Approach
Code with inline comments in C++
#include <bits/stdc++.h>
using namespace std;
string extract_ip(string ip_line){
stringstream ss(ip_line);
int count=4;
string ip;
while(count--){
ss>>ip;
}
return ip;
}
bool IP_compare(string ip1, string ip2){
return extract_ip(ip1)<extract_ip(ip2);
}
int main(){
ifstream infile("info.txt");
vector<string> allInfo;
string line;
//read all info
while(getline(infile, line)){
allInfo.push_back(line);
}
//sort allInfo using custom comparator
sort(allInfo.begin(), allInfo.end(), IP_compare);
//save sorted list in sorted.txt
ofstream outfile("sorted.txt");
for(string str:allInfo){
outfile<<str<<endl;
}
string ip;
do{
cout<<"Enter Ip for Search or 0 to exit: ";
//take input
cin>>ip;
//search for ip in ip_only vector
bool found=false;
for(string str:allInfo){
if(extract_ip(str)==ip)
{
cout<<"Found : "<< str<<endl;
found=true;
break;
}
}
if(!found)
cout<<"Not Found!"<<endl;
}while(ip!="0");
}
Input/Output
info.txt
Jun 11 23:26:10 908.93.383.85:4940 Failed password for admin
Aug 2 05:13:39 355.45.117.69:4551 Failed password for root
Oct 24 02:32:14 852.37.168.72:6796 Illegal user
sorted.txt
Aug 2 05:13:39 355.45.117.69:4551 Failed password for root
Oct 24 02:32:14 852.37.168.72:6796 Illegal user
Jun 11 23:26:10 908.93.383.85:4940 Failed password for admin
Console Input/Output
Get Answers For Free
Most questions answered within 1 hours.