2016-08-05 94 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[]),它必須返回一個值。