2015-04-12 72 views
0

我想創建一個將兩個字符串連接在一起的程序。 我的代碼創建了一個char[]strcat - 由兩個字符串組成。結果是混亂的垃圾。任何想法發生了什麼?我想象一下char[]已經充滿了垃圾,當我嘗試concat它,但我不確定。C concat兩個小字符串到一個較大的字符串

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

int main(){ 
    char* s1 = "this"; 
    char* s2 = "that"; 
    char s3[9]; 

    int i; 

    for(i = 0; i < 4; i++){ 
     printf("%c\n", s3[i]); 
    } 
    strcat(s3, s1); 
    for(i = 0; i < 4; i++){ 
     printf("%c\n", s3[i]); 
    } 
    strcat(s3, s2); 
    for(i = 0; i < 4; i++){ 
     printf("%c\n", s3[i]); 
    } 
} 

輸出:

@ 



@ 
t 


@ 
t 

回答

1

你要麼必須設置S3 [0] = '\ 0';或者你必須爲第一個使用strcpy。

s3 [0] ='\ 0';

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

int main(){ 
    char* s1 = "this"; 
    char* s2 = "that"; 
    char s3[9]; 
    int i; 

    s3[0] = '\0'; 

    for(i = 0; i < 4; i++){ 
     printf("%c\n", s3[i]); 
    } 
    strcat(s3, s1); 
    for(i = 0; i < 4; i++){ 
     printf("%c\n", s3[i]); 
    } 
    strcat(s3, s2); 
    for(i = 0; i < 4; i++){ 
     printf("%c\n", s3[i]); 
    } 
} 

的strcpy

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

int main(){ 
    char* s1 = "this"; 
    char* s2 = "that"; 
    char s3[9]; 

    int i; 

    for(i = 0; i < 4; i++){ 
     printf("%c\n", s3[i]); 
    } 
    strcpy(s3, s1); 
    for(i = 0; i < 4; i++){ 
     printf("%c\n", s3[i]); 
    } 
    strcat(s3, s2); 
    for(i = 0; i < 4; i++){ 
     printf("%c\n", s3[i]); 
    } 
} 
+0

謝謝,這個工作。我使用for循環遍歷s3並將所有值設置爲\ 0。有沒有更好的方法來創建一個可用的空字符串,或者這是唯一的方法? –

+0

@GraysonPike你不需要做所有職位,只需要第一個職位。 – Deanie

+0

啊,我明白了。再次感謝您的幫助。 –