Strange behavior with getline C++
<p>I am writing a simple program, where all the 'spaces' will be replaced by '%20'.</p>

<pre><code>#include &lt;iostream&gt;
#include &lt;string&gt;

using namespace std;

int main (int argc, char* argv[]){

    string input;
    cout &lt;&lt; "please enter the string where spaces will be replaced by '%20'" &lt;&lt; endl;
    getline(cin, input);
    //count the number of spaces
    int countSpaces = 0;
    for (int i = 0 ; i &lt; input.length() ; i++){
        if (input[i] == ' '){
            countSpaces++;

        }

    }

    int size = input.length() + (2 * countSpaces) + 1;
    //char cstr1[size];
    char *cstr1 = new char[size];
    char *cstr = cstr1;
    for (int i = 0 ; i &lt; input.length() ; i++){
        if(input[i] == ' '){ 
            *cstr++ = '%';
            *cstr++ = '2';
            *cstr++ = '0';
        }               
        else{   
            *cstr++ = input[i];

        }

    }
    *cstr == '\0';

    cout &lt;&lt; cstr1 &lt;&lt; endl;
    delete[] cstr1;

   return 0;

}
</code></pre>

<p>I get the following strange behavior:</p>

<ol>
<li><p>With the test input <code>"this is strange  "</code> I get <code>"this%20is%20strange%20%20his is"</code> , where I just expect <code>"this%20is%20strange%20%20"</code>  </p></li>
<li><p>If I hard code the same string, I get the correct results.</p></li>
<li><p>Replacing <code>char *cstr1 = new char[size];</code> with <code>char cstr1[size];</code> &amp; removing the <code>delete[]</code> while still fetching the input via <code>getline</code> also removes the error.</p></li>
</ol>

<p>I am using i686-apple-darwin10-g++-4.2.1:</p>

<p>Any help is much appreciated.</p>
