我正在使用 MSVS2010 编写一个 C++ 程序。我有一个值为 HAI\HOW_ARE\YOU
的字符串。我将它存储到文件中的字符串中(使用 istringstream 读取)。现在,我正在打开另一个文件,我必须检查是否有相同的字符串存在于任何行中。我使用了以下代码:
while(!file.eof())
{
getline(file,line_read);
if(line_read.find(search_word)!=string::npos) // search_word = "HAI\HOW_ARE\YOU"
break;
else
getline(file,readline);// skip a line
}
但即使 line_read
包含 search_word
,控制也会转到 else 部分。我知道这是由于字符串中的 \
字符引起的,因为以下代码有效:
while(!file.eof())
{
getline(file,line_read);
if(line_read.find("HAI\\HOW_ARE\\YOU")!=string::npos) \\ included double slash
break;
else
getline(file,readline);// skip a line
}
所以我尝试使用 Replace double slashes to four slashes 将 \
替换为 \\
.但它也将控制权传递给了 else
部分。
我无法通过手动输入字符串来找到,因为我必须以这种方式比较很多字符串。有什么办法可以解决吗?
提前致谢。
最佳答案
如果字符串是从文件中读取的,则不需要用双反斜杠替换反斜杠。
您只使用 \\
来表示源文件字符串中的单个反斜杠,以表明您的意思是反斜杠原样,而不是转义字符。
尝试运行以下代码,将查找字符串更改为您的查找字符串。
对我来说它打印了 4 行。
#include <string>
#include <fstream>
#include<iostream>
using namespace std;
string find_str; = "USB\\VID_04E8&PID_6860\\4df73c04056fbfa5";
int main()
{
ifstream input("input.txt");
ifstream fin("C:\\Windows\\Inf\\setupapi.dev.log");
string line;
while(std::getline(fin,line)){
if(line.find(find_str)!=string::npos){
cout<<line<<endl;
}
}
return 0;
}
编辑: 如果我从文件中读取搜索字符串,它将如下所示:
#include <string>
#include <fstream>
#include<iostream>
using namespace std;
int main()
{
ifstream input("input.txt");
ifstream fin("C:\\Windows\\Inf\\setupapi.dev.log");
string find_str;
string line;
input>>find_str;
while(std::getline(fin,line)){
if(line.find(find_str)!=string::npos){
cout<<line<<endl;
}
}
return 0;
}
如果 input.txt 文件是:
USB\VID_04E8&PID_6860\4df73c04056fbfa5
我得到了相同的结果。
关于c++ - 如何在 C++ 的一行中查找包含反斜杠字符的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26361120/