2013-05-26 63 views
1

請看下面的代碼添加:爲什麼 001時strcat的調用

char chs[100] = "Hello World"; 
char token[100]; 
int pos = -1; 
while((current = chs[++pos]) != '"'){ 
     strcat(token, &current); 
} 

但輸出是:

H\001e\001l\001l\001o\001 \001W\001o\001r\001l\001d 

任何想法?

+0

@mbratch輸出應該是Hello World – Foredoomed

+0

@Foredoomed你試圖去除字符串文字周圍的引號嗎?引號實際上並不是字符串的一部分!也許你應該從閱讀[書籍]開始(http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list)。 – Praetorian

+0

@Foredoomed,但這只是從'chs'到'token'的字符串副本?如果是這樣,那麼這就是'strcpy'的用途。你只需要做'strcpy(token,chs);'並且完成。不需要循環。還是有其他目的?如果你想使用'strcat',它需要兩個字符串參數都是零終止的。所以你至少需要設置'token [0] ='\ 0''來開始循環,就像我剛纔提到的那樣。 – lurker

回答

2

的strcat()需要一個空結束的字符串作爲它的輸入。所以strcat(令牌,當前爲&)將開始讀取當前的地址,並繼續前進,直到找到空值。就在偶然的情況下,當前的內存是「\ 001」,所以每次你執行strcat時,它都會將所有內容複製到令牌中。

您應該執行char current [] =「\ 0 \ 0」,然後爲其指定current [0] = chs [++ pos]。那樣的話,電流總是會有空終止。

2

您具有不確定的行爲

由於您的current未聲明,我猜這是一些初始化字符。你的 current = chs[++pos])設置字符,但strcat(token, &current);想要current是一個字符串,所以你在變量current之後保存了一些垃圾。請發表您的更多示例代碼進行進一步的分析

BTW '"'看起來錯Ç

0

使最小的變化,這是你的代碼的工作版本:

#include <string.h> 
#include <stdio.h> 

int main() 
{ 
    char current[2] = { 0x0, 0x0 }; // Will be null terminated 
    char chs[100] = "Hello World"; 
    char token[100] ; 
    int pos = -1; // Destination of strcat must also be null terminated 

    token[0] = '\0' ; 

    // String literals does not actually have " in memory they end in \0 
    while((current[0] = chs[++pos]) != '\0') 
    { 
      strcat(token, &current[0]); // Take the address of the first char in current      
    } 

    printf("%s\n", token) ; 

    return 0 ; 
} 

strcat預計源和目的地爲空終止字符串。在你的情況下,它看起來像current剛剛結束了一個\001後跟一個空終止符後,它在內存中。

相關問題