C++ 从字符串读取变量数据

C++ 从字符串读取变量数据,c++,C++,我正在阅读一个大的BAN日志文件,我想从这些BAN中指定该行中的一个名称(参见下面的John)。然后我只想打印出该行的IP。下面是示例日志文件中的几行: [13:42:51]詹姆斯·普雷斯顿(IP:11.111.11.11)被约翰禁止 [13:42:51]杰拉尔德·法默(IP:222.22.222.22)被詹姆斯禁止离线 [13:42:51]卢克·帕克(IP:33.33.333.333)被约翰禁止 到目前为止,我可以得到包含“john”的禁令行,但是我想从这些行中提取IP地址 int main(

我正在阅读一个大的BAN日志文件,我想从这些BAN中指定该行中的一个名称(参见下面的John)。然后我只想打印出该行的IP。下面是示例日志文件中的几行:

[13:42:51]詹姆斯·普雷斯顿(IP:11.111.11.11)被约翰禁止

[13:42:51]杰拉尔德·法默(IP:222.22.222.22)被詹姆斯禁止离线

[13:42:51]卢克·帕克(IP:33.33.333.333)被约翰禁止

到目前为止,我可以得到包含“john”的禁令行,但是我想从这些行中提取IP地址

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;
}
intmain(){
ifstreambanlogs;
BanLogs.open(“ban-2019.log”);
//检查文件是否已打开
if(BanLogs.fail()){

如评论中所述,cerr是一种选择


另一种方法是使用您已经在使用的
std::string::find
来选择相关行。您可以通过云搜索
“(IP:
来获取地址的起始位置(实际起始位置是
std::string::find
的结果加上搜索字符串长度的4)。然后您可以搜索“
””
以获取字符串中IP地址的结束位置。使用这两个位置,您可以使用提取包含IP地址的子字符串。

如注释中所述,是一个选项


另一种方法是使用您已经在使用的
std::string::find
来选择相关行。您可以通过云搜索
“(IP:
来获取地址的起始位置(实际起始位置是
std::string::find
的结果加上搜索字符串长度的4)。然后您可以搜索“
””
,以获取字符串中IP地址的结束位置。使用这两个位置,您可以使用提取包含IP地址的子字符串。

由于您是编程新手,以下是最普通的方法:

    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;
size\u t startIdx=item.find((IP:);
如果(startIdx==std::string::npos)继续;
startIdx+=5;//跳过“(IP:”部分
size_t endIdx=item.find('),startIdx+1);
如果(endIdx==std::string::npos)继续;

cout由于您是编程新手,以下是最普通的方法:

    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;
size\u t startIdx=item.find((IP:);
如果(startIdx==std::string::npos)继续;
startIdx+=5;//跳过“(IP:”部分
size_t endIdx=item.find('),startIdx+1);
如果(endIdx==std::string::npos)继续;

不能使用正则表达式?抱歉@G-man,我是编程新手,不知道你的意思?使用正则表达式?抱歉@G-man,我是编程新手,不知道你的意思?另一种方法是使用另一种方法是使用