Strange behavior with getline C ++

advertisements

I am writing a simple program, where all the 'spaces' will be replaced by '%20'.

#include <iostream>
#include <string>

using namespace std;

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

    string input;
    cout << "please enter the string where spaces will be replaced by '%20'" << endl;
    getline(cin, input);
    //count the number of spaces
    int countSpaces = 0;
    for (int i = 0 ; i < 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 < input.length() ; i++){
        if(input[i] == ' '){
            *cstr++ = '%';
            *cstr++ = '2';
            *cstr++ = '0';
        }
        else{
            *cstr++ = input[i];

        }

    }
    *cstr == '\0';

    cout << cstr1 << endl;
    delete[] cstr1;

   return 0;

}

I get the following strange behavior:

  1. With the test input "this is strange " I get "this%20is%20strange%20%20his is" , where I just expect "this%20is%20strange%20%20"

  2. If I hard code the same string, I get the correct results.

  3. Replacing char *cstr1 = new char[size]; with char cstr1[size]; & removing the delete[] while still fetching the input via getline also removes the error.

I am using i686-apple-darwin10-g++-4.2.1:

Any help is much appreciated.


The last line must be *cstr = '\0'; not ==