我有一個程序創建一個動態字符串的數據輸入(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
在該函數的調用三次一行用於連續打印的三組不同的數據。
「C++字符串不允許使用」是這個作業嗎? (然後需要作業標籤) – Rookie 2013-04-08 17:12:47
@Rookie:[標籤:家庭作業]標籤被刪除*長*前。 – 2013-04-08 17:14:04