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

时间:2011-04-30 20:36:12

标签: c++ string

我正在尝试编写一个将加载到文件中的小程序,将每行与特定的单词数组进行比较,如果该行中包含任何单词,那么我想“打印”该行。一个文件。

我目前的代码是:

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();
}

当我运行程序时,它将比较字符串,如果它匹配,它将只打印出特定的单词而不是字符串。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:3)

如果我正确理解您的问题,您需要检查该行是否包含其中一个单词并打印出来。

现在你正在做的是:

if(firewallLogString == wordsToFind[i])

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

相反,请检查单词是 字符串的一部分,如下所示:

if(firewallLogString.find(wordsToFind[i]) != string::npos)

答案 1 :(得分:0)

您的代码中存在错误。 在这一行

getline(firewallLog, firewallLogString);

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

答案 2 :(得分:0)

使用std :: string find方法查找模式词的出现次数。

相关问题