垃圾字符存储在数组中

时间:2012-04-07 06:02:11

标签: c++

我正在尝试从我的本地函数中从main发送到另一个字符的数组中复制数据,即使我在字符串的末尾添加'\0',我总是看到垃圾字符。

这是我的部分代码。

for (int i = 0; i < strlen(main) ; i++){
    if (main[i] != ';'){
        local[i] = main[i];  // Copy the characters until `;` isn't found
    } else {
        local[i] = '\0' ;   // If `;` found, null terminate the copied destination.
        break;
    }
}

所以基本上是从main发送的数据,例如像

look;can;you;see;me

My Local-----> 'look??y??>c?Lw?T?w??>c?2+a?'
Actual data in main---> 'look'

从上面的例子可以看出,我只是想得到第一个字而且我总是得到垃圾,我不知道为什么?

修改

这几乎是100%确定导致我出现问题的整个功能。

void myFunction(char main[ ]){


   for (int i = 0; i < strlen(main) ; i++){
    if (main[i] != ';'){
        local[i] = main[i];  // Copy the characters until `;` isn't found
    } else {
        local[i] = '\0' ;   // If `;` found, null terminate the copied destination.
        break;
    }
}


        if(main[i] != '\0'){


            int col = 0, row = 0;

            do {
                if(main[i] == ';' || main[i] == '\0') {
                    sending[row++][col] = '\0';
                    col = 0;
                } else {
                    sending[row][col++] = main[i];
                }
            } while(main[i++] != '\0');

        }



    }

2 个答案:

答案 0 :(得分:3)

如果是,你忘记了零点终止字符串;找不到 。一个简单的修复就是调整你的for循环,这样它也会在main中看到\ 0:

for (int i = 0; i <= strlen(main); i++) {

答案 1 :(得分:1)

标准库为您处理此问题。使用strchrstrncpy

size_t length = std::strlen(main);
const char* current_pos = main;
for (int i = 0; ; ++i) {
    size_t chars_remaining = length - std::distance(main, current_pos);
    const char* end_of_field = std::strchr(current_pos, ';');
    if (end_of_field == NULL) {
        std::strncpy(local[i], current_pos, chars_remaining + 1);
        // we're at the end of the input
        break;
    }
    else {
        size_t field_length = std::distance(current_pos, end_of_field);
        std::strncpy(local[i], current_pos, field_length);

        // don't forget to NUL-terminate the string
        local[i][field_length] = '\0';

        // go to next character for the next iteration through loop
        current_pos = end_of_field + 1;
    }
}

就个人而言,我更喜欢std::findstd::copy(来自<algorithm>):

size_t length = std::strlen(main);
const char* current_pos = main;
for (int i = 0; ; ++i) {
    size_t chars_remaining = length - std::distance(main, current_pos);
    const char* end_of_field = std::find(current_pos, current_pos + chars_remaining, ';');
    char* output_end = std::copy(current_pos, end_of_field, local[i]);

    // don't forget to NUL-terminate the string
    *output_end = '\0';

    // if we're at the end of main, then we're done;
    // we're at the end if we're on a NUL character
    if (*end_of_field == '\0')
        break;

    // go to next character for the next iteration through loop
    current_pos = end_of_field + 1;
}

不是我写过的最漂亮的代码,但这很大程度上是由于使用了C风格的字符串和指针算法,考虑到原始问题,这看起来并不可避免。另外,我还没有进行必要的溢出检查。这样做很容易,但使用std::vector<std::string>更容易,让标准库为您担心。