如何将字符串与某些单词进行比较,如果找到匹配,则打印整个字符串
How to compare a string with certain words and if a match is found print the whole 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();
}
当我运行程序时,它将比较字符串,如果匹配,它将只打印特定的单词而不是字符串。
如果我正确理解了你的问题,你要检查行是否包含一个单词,如果包含,则打印它。
现在你正在做的是:
if(firewallLogString == wordsToFind[i])
检查字符串是否与完全匹配。因此,如果字符串包含中的一个单词,但其中包含其他单词,则测试将失败。
相反,检查单词是否是字符串的一部分,如下所示:if(firewallLogString.find(wordsToFind[i]) != string::npos)
你的代码有问题。在这一行
getline(firewallLog, firewallLogString);
你正在读取一行,而不是一个单词,但随后你将整行与数组中的一个单词进行比较。你的IF实际上不能工作。相反,您需要使用strstr方法来查找firewallLogString中的任何单词,如果找到,则执行其余代码。
使用std::string的find方法查找模式字的出现
相关文章:
- 有没有办法将字符串打印为文字?
- 如何通过标准字符串打印 ostream 变量的值?
- 这个随机字符串打印代码有什么问题?
- 比较 C++ 字符串打印中的两个整数数组
- 在C++中从后缀表达式字符串打印单个操作
- 没有得到 ASCII 编号 = 7 的字符串打印输出
- C++字符串到字符串打印不正确,无法获取 unicode 路径
- 如何从数组 c++ 中的字符串打印第 N 个字符
- 将 LPCWSTR 字符串打印到文件
- C++正在将DWORD_PTR*字符串打印到文件中
- 使用#define字符串打印f和警告
- 使用格式字符串打印类
- 如何将字符转换为字符串,并从字符串打印到main函数
- 将vector中结构体的成员字符串打印到cout流
- fprintf() / std::cout 不会将部分字符串打印到 stdout/stderr
- 为什么ostream为定义为' volatile char[] '的字符串打印' 1 ' ?
- c++文件读取和字符串打印
- 如何使用一个字符串打印此unicode行
- 按字符串打印日期
- 如何用c++将字符串打印到控制台