Hi,

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 );
        pos++;
    }
    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.

Recommended Answers

All 2 Replies

'\' 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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.