Reputation: 69
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;
}
Upvotes: 0
Views: 114
Reputation: 1637
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.
Upvotes: 2
Reputation: 511
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
.
Upvotes: 0