I am writing a C++ program to "find and replace" strings. Following is the code:

void pt::replace()
    string str( textpath );
    string searchString( "\" );
    string replaceString( "\\" );

    assert( searchString != replaceString );

    string::size_type pos = 0;
    while ( (pos = str.find(searchString, pos)) != string::npos ) {
        str.replace( pos, searchString.size(), replaceString );
    cout << str << endl;

Whenever I type any text inside searchString(), it works fine but problem arises when I type "\" inside search or replace function. I think I need some type of datatype conversion. Please help me on this.

'\' is typically called an "escape sequence". If you are actually trying to search for a '\', you need to use a '\\'. Can you explain an input that is giving you an incorrect behavior?

Well \ is a special character. C++ still caries the remnants of C formatted strings, for good reason. So "\\" actually means the single character "\" and "\" or '\' is an error. This is because you use \ to enter special characters like '\t' for tab, '\n' for newline, '\r' for carriage-return, and some others too. You have to understand that searching for '\' to replace it with '\\' is not going to work. Although a string might be displayed on the console as a single '\' it will actually be represented in formatted string format as '\\'. If you want to search for the single character '\', you have to search for the _single_ character '\\', it sounds confusing but that's how it is.

This article has been dead for over six months. Start a new discussion instead.