PRB: STL string Class replace Function Does Not Work as Expected

Last reviewed: July 24, 1997
Article ID: Q168377
The information in this article applies to:
  • The Standard C++ Library included with: - Microsoft Visual C++, 32-bit Editions, versions 4.2, 5.0

SYMPTOMS

The string::replace member function does not work as expected. This is because the same string object is used for modification and input. Many data manipulation routines do not check for overlapping or identical arguments, causing unexpected results.

RESOLUTION

Create a temporary copy of the string as shown below:

   s1.replace (1,2,string("c"));

STATUS

This behavior is by design.

MORE INFORMATION

Steps to Reproduce Behavior

The sample code below demonstrates the behavior reported in the SYMPTOMS section.

    #include <iostream>
    #include <string>
    using namespace std ;

    void f1()
     {
      string s ("abcd");
      s.replace (1,2,s,2,1);
      cout << "s (should be 'acd'): " << s << endl << endl;
     }

    int main ()
     {
       f1();// prints "add" instead of "acd"
       return 0 ;
     }
 

	
	


Keywords : STLIss
Version : 4.2 5.0
Platform : NT WINDOWS
Issue type : kbprb


THE INFORMATION PROVIDED IN THE MICROSOFT KNOWLEDGE BASE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL MICROSOFT CORPORATION OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF MICROSOFT CORPORATION OR ITS SUPPLIERS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES SO THE FOREGOING LIMITATION MAY NOT APPLY.

Last reviewed: July 24, 1997
© 1998 Microsoft Corporation. All rights reserved. Terms of Use.