私はすべての 'スペース'が '%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 ++を使用しています
。
デバッガでコードをステップ実行して、実際に第2ループで何が起こっているのか確認しましたか? –