如何将字符串与某些单词进行比较,如果找到匹配,则打印整个字符串

How to compare a string with certain words and if a match is found print the whole string

本文关键字:字符串 打印 如果 比较 单词进      更新时间:2023-10-16

我正在尝试编写一个小程序,它将加载一个文件,将每行与特定的单词数组进行比较,如果该行中有这些单词,那么我想将该行"打印"到文件中。

我当前的代码是:

int main()
{
    string wordsToFind[13] = 
    {"MS SQL", "MySQL", "Virus", "spoof", "VNC", "Terminal", "imesh", "squid",
    "SSH", "tivo", "udp idk", "Web access request dropped", "bounce"};
    string firewallLogString = "";
    ifstream firewallLog("C:\firewalllogreview\logfile.txt");
    ofstream condensedFirewallLog("C:\firewalllogreview\firewallLog.txt");
    if(firewallLog.fail())
    {
        cout << "The file does not exist. Please put the file at C:\firewalllogreview and run this program again." << endl;
        system("PAUSE");
        return 0;
    }
    while(!firewallLog.eof())
    {
        getline(firewallLog, firewallLogString);
            for(int i = 0; i < 13; i++)
            {
                if(firewallLogString == wordsToFind[i])
                {
                    firewallLogString = firewallLogString + 'n';
                    condensedFirewallLog << firewallLogString;
                    cout << firewallLogString;
                }
            }
    }
    condensedFirewallLog.close();
    firewallLog.close();
}

当我运行程序时,它将比较字符串,如果匹配,它将只打印特定的单词而不是字符串。

如果我正确理解了你的问题,你要检查行是否包含一个单词,如果包含,则打印它。

现在你正在做的是:

if(firewallLogString == wordsToFind[i])

检查字符串是否与完全匹配。因此,如果字符串包含中的一个单词,但其中包含其他单词,则测试将失败。

相反,检查单词是否是字符串的一部分,如下所示:
if(firewallLogString.find(wordsToFind[i]) != string::npos)

你的代码有问题。在这一行

getline(firewallLog, firewallLogString);

你正在读取一行,而不是一个单词,但随后你将整行与数组中的一个单词进行比较。你的IF实际上不能工作。相反,您需要使用strstr方法来查找firewallLogString中的任何单词,如果找到,则执行其余代码。

使用std::string的find方法查找模式字的出现