나는 모든 '공백'이 '% 20'으로 대체되는 간단한 프로그램을 작성하고 있습니다. 나는 동일한 문자열, 열심히 코드를 얻을 경우 그냥 "this%20is%20strange%20%20"
getline C++에서 이상한 동작
기대 "this is strange "
내가 "this%20is%20strange%20%20his is"
얻을 테스트 입력으로
:
#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; }
나는 다음과 같은 이상한 행동을 얻을 올바른 결과.
여전히
getline
통해 입력을 가져 오는 동안char cstr1[size];
&을 제거하여delete[]
char *cstr1 = new char[size];
장착 또한 에러를 제거한다. 어떤 도움이 많이 감사합니다: 4.2.1 - 내가는 i686-사과 darwin10-g ++를 사용하고
.
디버거의 코드를 단계별로 실행하여 실제로 두 번째 루프에서 진행중인 작업을 확인해 보았습니까? –