0

I am reading through a large log file of bans, and from those bans I want to specify a name within that line (see John below). I then want to print out only the IP of that line. Here are a few lines from an example log file:

[13:42:51] james preston (IP: 11.111.11.11) was banned by john

[13:42:51] gerald farmer (IP: 222.22.222.22) was offline banned by James

[13:42:51] luke parker (IP: 33.33.333.333) was banned by john

So far I can get the lines of the bans containing "john" however I would like to then extract the IP address from those lines.

int main() {
ifstream BanLogs;
BanLogs.open("ban-2019.log");

// Checking to see if the file is open
if (BanLogs.fail()) {
    cerr << "ERROR OPENING FILE" << endl;
    exit(1);
}

string item;
string name = "john";
int count = 0;


//read a file till the end
while (getline(BanLogs, item)) {
    // If the line (item) contains a certain string (name) proceed.
    if (item.find(name) != string::npos) {
        cout << item << endl;
        count++;
    }
}

cout << "Number of lines " << count << endl;
return 0;
}
2
  • 1
    Use regular expressions? Commented Jan 21, 2019 at 6:28
  • Sorry @G-man, I am new to programming and am unaware of what you mean? Commented Jan 21, 2019 at 6:33

2 Answers 2

2

Since you are new to programming, here is the most vanilla way:

    size_t startIdx = item.find("(IP: ");
    if (startIdx == std::string::npos) continue;
    startIdx += 5; // skip the "(IP: " part
    size_t endIdx = item.find(')', startIdx + 1);
    if (endIdx == std::string::npos) continue;
    cout << item.substr(startIdx, endIdx - startIdx) << endl;

This kind of jobs are much easier to do with scripting languages, i.e. Python.

Sign up to request clarification or add additional context in comments.

Comments

0

As mentioned in the comments, regular expressions are one option.

Another would be to use std::string::find which you are already using to select the relevant lines. You cloud search for "(IP:" to get the starting position of the address (The actual starting position is the result of std::string::find plus 4 for the length of the search string). Then you can search for ")" to get the end position of the IP address in the string. Using these two positions you can extract a substring containing the IP address by using std::string::substr.

1 Comment

Another way is to use std::sscanf()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.