2012-01-24 105 views
2

我在寫一個簡單的程序,其中所有'空格'將被'%20'替換。getline C++的奇怪行爲

#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; 

} 

我得到以下奇怪的現象:

  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-蘋果darwin10-G ++ - 4.2.1:

任何幫助深表感謝。

+2

您是否嘗試單步調試調試器中的代碼以查看第二個循環中實際發生了什麼? –

回答

6

最後一行必須是* cstr ='\ 0';沒有==

+2

好的結果 - 還要注意,如果OP用'g ++ -Wall ...'編譯,編譯器就會爲他發現錯誤。 –

+1

謝謝,它解決了這個問題。看起來我睡眠不足:P – shiraz

+0

這些時候我也想拍我的編譯器 – Ulterior

2

更改*cstr == '\0';在你的代碼的末尾*cstr = '\0';
中提琴!

2
*cstr == '\0'; 

此行檢查*cstr等於'\0'與否並返回10相應

,只要你想在字符串 的末尾插入\0字符所以寫單,這是錯誤=而不是雙重=