数据不存储在数组中

时间:2012-02-25 17:55:45

标签: c++ arrays

我正在尝试将一些数据存储在数组调用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'

3 个答案:

答案 0 :(得分: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 :(得分:2)

一个问题是你使用t作为holder的索引和输入字符串的索引。这可能适用于第一部分,但不适用于之后的部分。

您还希望在按分号时存储空终止符。

答案 2 :(得分:1)

最后一个条件if (holder[d][t] == '\0')出现问题。 在这种情况下有两个字符(\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++;
}