2

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.

1
  • 2
    Did you try stepping through the code in a debugger to see what is actually going on in the second loop ? Commented Jan 24, 2012 at 9:12

3 Answers 3

6

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

Sign up to request clarification or add additional context in comments.

3 Comments

Good catch - note also that if the OP had compiled with g++ -Wall ... the compiler would have caught the error for him.
Thanks, it solved the problem. Looks like I am sleep deprived :P
These are the times I would like to slap my compiler too
2

Change the *cstr == '\0'; in the end of your code to *cstr = '\0';
Violà!

Comments

2
 *cstr == '\0'; 

this line checks if *cstr is equal to '\0' or not and return 1 or 0 accordingly

that is wrong as you want to insert the \0 character at the end of the string so write single = instead of double =

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.