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.

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

int main()

void nonmember()
std::string line;
std:: ifstream myinput("weblog.txt");
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;"sortedweblog.txt");
for(int i=0; i<webvector.size(); i++)
myfile << webvector[i];

void uniqueipnonmember()
int i = 0;
string ip = webvector[i].substr(0,14);
std:: cout<< ip << std::endl;
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
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::vector<string>::iterator up;
up= std::upper_bound (webvector.begin(), webvector.end(), (*it),mysmaller);

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.