2013-04-08 34 views
-3

我有一個程序創建一個動態字符串的數據輸入(C++字符串不允許使用),看起來像這樣(而不是日期可以基本上任何其他數據和數據塊的數量沒有給出):C++將字符串拆分爲動態字符數組,表現不可預知

2004-01-18 | 2005-01-18 |

我需要處理的字符串是將它分成一個可用於打印的單數據塊的2d char數組。我的代碼看起來是這樣的:

char** CRegister::Split(char *st, int& parts, int& maxChars) const{ 

    parts = 0; 
    maxChars = 0; 
    int maxtmp = 0; 
    int j = 0; 

    /* Calculating the number of data blocks in the string */ 

    while(st[j]){ 
     if(st[j] == '|'){ 
      parts++; 
     } 
     j++; 
    } 
    j = 0; 

    /* Calculating the longest data block length for array initialization */ 

    while(st[j]){ 
     if(st[j] != '|'){ 
      maxtmp++; 
     } 
     else{ 
      if(maxtmp > maxChars){ 
       maxChars = maxtmp; 
      } 
      maxtmp = 0; 
     } 
     j++; 
    } 
    j = 0; 

    cout << "!!!!!-----!!!!!-" << st << "-!!!!!!!-----!!!!!" << endl; 

    /* Initialization of the dara array */ 

    char **array = new char*[parts]; 
    for(int i = 0; i < parts; i++){ 
     array[i] = new char[maxChars]; 
    } 

    /* Filling the array with data blocks */ 

    int p = 0; 
    for(int i = 0; i < parts; i++){ 
     while(st[j] != '|'){ 
      array[i][p] = st[j]; 
      j++; 
      p++; 
     } 
     if(st[j] == '|'){ 
      j++; 
     } 
     p = 0; 
    }  
    return array;  
} 

從它只是我需要它的方式在大多數情況下,但問題是它往往有時不可預測的行爲,敗壞了整個程序 - 數據塊不會在他們應該在的地方結束,並且會添加一堆其他角色(通常是以前使用的單詞的一部分)。那麼結果如下所示(與之間的線「!!!!! ----- !!!!! - 」是經預處理的陣列)

!!!!!-----!!!!!-2003-01-18|-!!!!!!!-----!!!!! 
!!!!!-----!!!!!-Whiston's street|-!!!!!!!-----!!!!! 
!!!!!-----!!!!!-Miami|-!!!!!!!-----!!!!! 

2003-01-18 Whiston's street Miami 

!!!!!-----!!!!!-2004-01-18|2005-01-18|-!!!!!!!-----!!!!! 
!!!!!-----!!!!!-Whiston's street|Someone's streetz|-!!!!!!!-----!!!!! 
!!!!!-----!!!!!-Miami|Siberia|-!!!!!!!-----!!!!! 

2004-01-18 Whiston's street Miami 
2005-01-18street Someone's streetz Siberia 

!!!!!-----!!!!!-2004-01-18|-!!!!!!!-----!!!!! 
!!!!!-----!!!!!-Whiston's street|-!!!!!!!-----!!!!! 
!!!!!-----!!!!!-Miami|-!!!!!!!-----!!!!! 

2004-01-18 Whiston's street Miami 

!!!!!-----!!!!!-2004-01-18|-!!!!!!!-----!!!!! 
!!!!!-----!!!!!-Whiston's street|-!!!!!!!-----!!!!! 
!!!!!-----!!!!!-Miami|-!!!!!!!-----!!!!! 

2004-01-18streetz Whiston's street Miami 

在該函數的調用三次一行用於連續打印的三組不同的數據。

+0

「C++字符串不允許使用」是這個作業嗎? (然後需要作業標籤) – Rookie 2013-04-08 17:12:47

+0

@Rookie:[標籤:家庭作業]標籤被刪除*長*前。 – 2013-04-08 17:14:04

回答

1

如果您不能使用標準字符串類,請編寫您自己的簡化版本,然後使用它。

然後與std::vector大致相同 - 使用它,或者寫一個你自己的簡化版本。

當你完成這兩項工作後,編寫這個函數來解析輸入到my_vector<my_string>應該是非常微不足道的。

+0

謝謝你的回答,不幸的是,矢量也是不允許的,反正我也不太熟悉,所以我不能寫它。另外,我已經完成了整個程序並且正在工作,所以這意味着我會承擔更多的工作時間,我承擔不起:(假設我只需要弄清楚這個問題有什麼問題。 – Geroth 2013-04-08 17:48:09