2012-02-25 48 views
0

我試圖將一些數據存儲在陣列通話holder,問題是,當我顯示陣列什麼是店它,我不知道什麼是錯的,甚至儘管邏輯似乎適合我。數據來自數組調用sender我正在使用二維數組在MAX處將其存儲爲5。數據不存儲在陣列中

 for (int t = 0; t < strlen(sender) && stop == false; t++){ // stop is the bool that created to break the loop 
      if (sender[t] != ';'){ // all the data being store in the holder will be separated by ';' 
       holder[d][t] = sender[t]; 
      } 
      if (sender[t] == ';') // if the sender at position of 't' number meet ';' then plus one to start store the next data 
       d++; 
      if (holder[d][t] == '\0'){ // if it meet the '\0' then exit from the for loop 
       holder[d][t] = '\0'; // If `;` found, null terminate the copied destination. 
       stop = true; 

      } 
     } 

這是發送者陣列"Hello;How;Is;Good Bye"

輸出是

Your holder-----> '

Actual holder---> 'Hello'

+1

是否有d起始值? (在循環之前?) '持有者[d] [t] =發件人[t];' – 2012-02-25 17:58:05

+4

請您能否正確縮進您的代碼片段? – 2012-02-25 17:58:43

+0

@OfirBaruch是的,它初始化爲'0' – Ali 2012-02-25 17:59:03

回答

3

我不明白你爲什麼不能使用break。也許你可以澄清練習的目的?否則,也許這個代碼解決了你的問題?我通常會使用了另一種技術,但既然你說你不能使用break ...

int pos = 0, col = 0, row = 0; 
do { 
    if(';' == sender[pos] || 0 == sender[pos]) { 
    holder[row++][col] = 0; 
    col = 0; 
    } else { 
    holder[row][col++] = sender[pos]; 
    } 
} while(0 != sender[pos++]); 
+1

+1,我正在處理用'for'循環發佈幾乎相同的代碼。 – Blastfurnace 2012-02-25 19:15:21

+1

@Blastfurnace是的,我也會用一個'for'循環,檢查內部0和'break'出去,但是沒有可能使用'break'我認爲這樣更好,因爲你需要以某種方式終止最後的子字符串。 (在循環之外做它似乎對我來說很難看。) – 2012-02-25 19:22:20

+1

感謝這段代碼爲我工作我可能會想出辦法以我自己的方式編寫它:/ – Ali 2012-02-25 19:26:59

2

一個問題是,使用的是噸兩者的索引爲保持器和您的輸入字符串的索引。這可能適用於第一部分,但不適用於之後的部分。

您也想存儲空終止符,當你打一個分號。

+0

那麼,我雖然沒有那個,但即使是第一個似乎沒有工作? :( – Ali 2012-02-25 18:02:38

1

有一個與最後一個條件if (holder[d][t] == '\0')問題。 有2個字符在這種條件下(\0),但holder[d][t]只有一個字符,因此 該條件將永遠不會true。 接下來的代碼是什麼?

int aStringLength = strlen(sender); 
int t = 0; 
while(stop == false) 
{ 
if(t == aStringLength) 
    stop = true; 

if(sender[t] != ';') 
{ 
    holder[d][i] = sender[t]; 
    i++; 
} 
else 
{ 
    d++; 
    i = 0; 
} 

t++; 
} 
+1

你可以寫'for(int t = 0;; ++ t)'而不是使用while循環和兩個附加語句。 '出來的循環,而不是分配一個布爾標誌? – 2012-02-25 18:54:42

+0

嗨,謝謝,我仍然得到空結果:( – Ali 2012-02-25 18:58:02

+1

@aliquis,你是對的。阿里,讓我們打破這個代碼 - 添加打印命令,所有的在每一步的變量。 我們在這裏失蹤somehthing。 – 2012-02-25 19:01:58