我正在编写一个简单的程序,其中所有'空格'将被'%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;
}
Run Code Online (Sandbox Code Playgroud)
我得到以下奇怪的行为:
随着测试输入,"this is strange "我得到了"this%20is%20strange%20%20his is",我期待的地方"this%20is%20strange%20%20"
如果我硬编码相同的字符串,我得到正确的结果.
更换char *cstr1 = new char[size];与char cstr1[size];&除去delete[]仍然撷取输入经由getline还去除该错误.
我正在使用i686-apple-darwin10-g ++ - 4.2.1:
任何帮助深表感谢.
| 归档时间: |
|
| 查看次数: |
262 次 |
| 最近记录: |