2016-08-05 99 views
1

这里练习使用指针的时候是我的程序:越来越怪异输出在C

#include <stdio.h> 

int tokenCopy(char* dest, const char* src, int destSize) 
{ 
    int i; 
    for (i = 0; i < destSize-1; i++) { 
     if (src[i] != '\0' && src[i] != EOF && src[i] != ' '){ 
      dest[i] = src[i]; 
     } else { 
      dest[i] = '\0'; 
      break; 
     } 
    } 
    return i; 
} 

int main() 
{ 
    char buff[5]; 
    int n = tokenCopy(buff, "This is a string", 5); 
    printf("%d '%s'\n", n, buff); 
} 

我试图用这个复制从字符串中提取到另一个字符串的字符串。有了这个测试用例,我应该得到4 'This'。但我得到4 'This�'。我知道我的循环以某种方式终止索引比它应该是,但我不知道如何解决它。

我知道有一个内置的功能可以帮助我这种情况,但我真的想找出问题,感谢

+2

@iwin:它不起作用。如果目标缓冲区长度为50个字节,我们将12个字符串复制到它中,索引12到50中的字符将为垃圾 – naccyde

回答

1

for循环运行,直到它完成(在else情况下,循环内绝不会发生),然后您只需从函数返回而不添加终止符到目标字符串。

您需要在之后添加终止符循环,而不是在循环内的else


固定功能应该像

int tokenCopy(char* dest, const char* src, int destSize) 
{ 
    int i; 
    for (i = 0; i < destSize-1; i++) { 
     if (src[i] != '\0' && src[i] != ' '){ 
      dest[i] = src[i]; 
     } else { 
      // Don't terminate here, just break out of the loop 
      break; 
     } 
    } 
    dest[i] = '\0'; // Terminate string 
    return i; 
} 

请注意,我也去掉了EOF检查,这几乎是无用的,因为没有标准的输入功能,应该把它写入到在数组中。还有一个问题,即将int的值-1(这是什么EOF扩展到)到char-1将不会按预期工作。如果您检查大多数返回字符的输入函数,则会看到它们返回int

+0

嗨Joachim,感谢您的回复! – chrisgjh

+0

是啊!!!!你是如此的正确。谢谢!!!!!!!!!!! – chrisgjh

1

它看起来像你的函数不会在字符串的末尾插入\0destSize值为5,因此一旦复制s字符,下一次迭代将停止循环,因为i将低于destsize - 1,因此else子句将不会被处理。

要绕过这一点,你应该for循环后插入\0,像这样:

int i; 
for (i = 0; i < destSize-1; i++) { 
    if (src[i] != '\0' && src[i] != EOF && src[i] != ' '){ 
     printf("Copy %c\n", src[i]); 
     dest[i] = src[i]; 
    } 
} 

dest[i] = '\0'; 

return i; 

而且,你的条件src[i] != EOF是无用的。您的主要功能也不是标准的,它应该是int main(void)int main(int argc, char *argv[]),它必须返回一个值。