substring, loops and writing to a file

Here are the requirements for a project I am working on.
Write a function that will write only unique ip addresses to a file (just the ip address, not the entire line).
Write a function that will search for an ip address and display all page requests for that ip address.
The ip is pulled from a "weblog.txt" file which has been put into a vector and sorted. I am having trouble with the loop to pull only unique ip addresses from the vector.
[code]
#include<iostream>
#include<vector>
#include<fstream>
#include<string>
#include<algorithm>

void nonmember();
void sortnonmember(std::vector<std::string>& webvector);
void writenonmember();
void uniqueipnonmember();
void findnonmember();
using namespace std;
std::vector<string> webvector;

int main()
{
nonmember();
sortnonmember(webvector);
writenonmember();
system("pause");
}

void nonmember()
{
std::string line;
std:: ifstream myinput("weblog.txt");
if(myinput.is_open())
{
while(getline(myinput,line))
{
webvector.push_back(line);
}
}
else std:: cout<< "file not found"<< std:: endl;
}

void sortnonmember(std::vector<std::string>& webvector)
{
sort(webvector.begin(), webvector.end());
std::cout << webvector[0] << std::endl;
std::cout << webvector[1] << std::endl;
}

void writenonmember()
{
std::ofstream myfile;
myfile.open("sortedweblog.txt");
for(int i=0; i<webvector.size(); i++)
{
myfile << webvector[i];
}
myfile.close();
}

void uniqueipnonmember()
{
int i = 0;
string ip = webvector[i].substr(0,14);
std:: cout<< ip << std::endl;
}
/[code]
Last edited on
First a few comments:
1. Try not to use global variables. Your functions can pass/return variables, so try that instead.
2. An example of the lines in weblog.txt would have been nice. For this discussion, I will assume that each line contains xxx.xx.xxx.xx/folder/page.html
3. If that is the case, use find_first_of function for strings to find the position of "/", and the IP address is the substring up to that position. For the following functions, I assume that you can write a function std::string getIP(std::string) that just returns the IP

Now here is how I would look for unique IP addresses:

bool mysmaller (std::string x, std::string y) { return (getIP(x)<getIP(y)); }
void uniqueIP(std::vector<std::string>& webvector)
{
for (std::vector<string>::iterator it = webvector.begin() ; it != webvector.end(); )
{
std::cout<<getIP(*it)<<std::endl;
std::vector<string>::iterator up;
up= std::upper_bound (webvector.begin(), webvector.end(), (*it),mysmaller);
it=++up;
}
}

For displaying all lines with the same IP, use the equal_range algorithm, with the same mysmaller comparison function
Topic archived. No new replies allowed.