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:
-
With the test input
"this is strange "I get"this%20is%20strange%20%20his is", where I just expect"this%20is%20strange%20%20" -
If I hard code the same string, I get the correct results.
-
Replacing
char *cstr1 = new char[size];withchar cstr1[size];& removing thedelete[]while still fetching the input viagetlinealso 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 ==