0

我正在尝试将数据从从主发送到本地函数中的另一个字符数组中复制,即使我'\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');

        }



    }
4

2 回答 2

3

如果 ; 你忘记了处理零终止字符串 没有找到。一个简单的解决方法是调整你的 for 循环,这样它也能在 main 中看到 \0:

for (int i = 0; i <= strlen(main); i++) {
于 2012-04-07T06:21:13.573 回答
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::findand std::copy(from <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>并且让标准库为您担心。

于 2012-04-08T09:03:04.210 回答