getline C++的奇怪行为

shi*_*raz 2 c++

我正在编写一个简单的程序,其中所有'空格'将被'%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)

我得到以下奇怪的行为:

  1. 随着测试输入,"this is strange "我得到了"this%20is%20strange%20%20his is",我期待的地方"this%20is%20strange%20%20"

  2. 如果我硬编码相同的字符串,我得到正确的结果.

  3. 更换char *cstr1 = new char[size];char cstr1[size];&除去delete[]仍然撷取输入经由getline还去除该错误.

我正在使用i686-apple-darwin10-g ++ - 4.2.1:

任何帮助深表感谢.

xpa*_*pad 6

最后一行必须是*cstr ='\ 0'; 不是==

  • 好的注意事项 - 请注意,如果OP使用`g ++ -Wall ...编译,编译器会为他捕获错误. (2认同)