简体   繁体   中英

How to find a string containing backslash character in a line in C++?

I am using MSVS2010 to code a C++ program.I have a string with value HAI\\HOW_ARE\\YOU . I stored it into the string from a file(read using istringstream). Now, I am opening another file and I have to check whether the same string exists in any of the lines. I used the following code:

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
}

But even if line_read contains search_word , the control goes to else part. I understood that it is due to the \\ character in the string because the following code worked:

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
}

So I tried replacing \\ by \\\\ using Replace double slashes to four slashes . But it also passed control to else part.

I cannot find by manually typing the string as I have to compare a lot of strings in this manner. Is there any way to solve this?

Thanks in advance.

If a string had read from a file, you don't need to replace the backslashes with double backslashes.

you only uses \\\\ to represent a single backslash in strings on source files, to indicate you mean the backslash as is, not as escape character.

Try to run the following code, change the find string to your find string.

For me it printed 4 lines.

#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;
}

EDIT: if I read the search string from a file it will look like this:

#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;
}

If input.txt file is:

USB\VID_04E8&PID_6860\4df73c04056fbfa5 

I'm getting the same results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM