title: C++ Sanitize string function
body: <p>I need to build my own sanitize function for the following chars:</p>
  
  <pre><code>', ", \, \n, \r, \0 and CTRL-Z
  </code></pre>
  
  <p>I want to make sure that the following code will do the trick with no side effects:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;string&gt;
  #include &lt;memory&gt;
  #include &lt;sstream&gt;
  #include &lt;iomanip&gt;
  #include &lt;algorithm&gt;    
  
  void sanitize (std::string &amp;stringValue)
  {
      stringValue.replace(stringValue.begin(), stringValue.end(), "\\", "\\\\");
      stringValue.replace(stringValue.begin(), stringValue.end(), "'", "\\'");
      stringValue.replace(stringValue.begin(), stringValue.end(), "\"", "\\\"");
      stringValue.replace(stringValue.begin(), stringValue.end(), "\n", "");
      stringValue.replace(stringValue.begin(), stringValue.end(), "\r", "");
      stringValue.replace(stringValue.begin(), stringValue.end(), "\0", "");
      stringValue.replace(stringValue.begin(), stringValue.end(), "\x1A", "");
  }
  
  int main()
  {
      std::string stringValue = "This is a test string with 'special //characters\n";
  
      std::cout &lt;&lt; stringValue &lt;&lt; std::endl;
  
      sanitize(stringValue);
  
      std::cout &lt;&lt; stringValue &lt;&lt; std::endl;
  }
  </code></pre>
  
  <p>This code is not working. Error:</p>
  
  <pre><code>    terminate called after throwing an instance of 'std::length_error'
    what():  basic_string::_M_replace
        1 
        1 This is a test string with 'special //characters
  </code></pre>
  
  <p>Original code <a href="http://coliru.stacked-crooked.com/a/4e5e9e1d02d79094" rel="nofollow">here</a></p>