2013-05-03 55 views
1

我想知道爲什麼字符數組的顯示是短的幾個字符。但是,當我使用長度+ 2時,會顯示所有字符。我不確定我做錯了什麼。您的幫助將不勝感激。我正在使用Dev-C++我的char數組的顯示是最後幾個字符的縮寫。 C++

#include <iostream> 
#include <string.h> 


using namespace std; 

char *Appendstring(char *a, char *b, char *c, char *d, char *e) // will append b to the end of a 
{ 
// char *buffer = new char[strlen(a)+strlen(b)+1]; 

static char buffer[90]; 

    char *p=buffer; 
    while(*p++=*a++); // Copy a into buffer 
    while(*p++=*b++); // Copy b into buffer right after a 
    while(*p++=*c++); // Copy c into buffer right after b 
    while(*p++=*d++); // Copy d into buffer right after c 
    while(*p++=*e++); // Copy e into buffer right after d 
    *p=0; // Null-terminate the string 
    return buffer; 
} 

int main() 
{ 
    char *new_string; 
    int length; 
    char *str="Because"; 
    char *add="it has been"; 
    char *addstr1="very warm"; 
    char *addstr2="lately"; 
    char *addstr3="Summer is coming!"; 


    length=strlen(str)+strlen(add)+strlen(addstr1)+strlen(addstr2)+strlen(addstr3)+1; //total length of the new string 

    new_string=Appendstring(str, add, addstr1, addstr2, addstr3); 
    for (int i=0; i<=length+2; i++) //Why do I need to do length+2 to have all characters displayed??? 
    cout<<new_string[i]; 

    return 0; 
} 

回答

3

因爲您的字符串複製代碼是錯誤的。它也複製字符串末尾的空字節。

試試這個

while (*a) // Copy a into buffer 
    *p++ = *a++; 
while (*b) // Copy b into buffer 
    *p++ = *b++; 

+1

+1。像這樣的問題正是爲什麼人們應該在C++而不是char數組中使用'std :: string'。 – Angew 2013-05-03 17:31:57

+0

這是嘗試你的建議之後的輸出: 「因爲它非常熱情,夏天來了!」而我目前的clode的輸出是:「」因爲它最近一直很溫暖夏天是comi。「 – T4000 2013-05-03 17:34:51

+0

@Angew,分配的要求是使用動態字符數組,並將它們附加在一起。我不允許使用std :: string – T4000 2013-05-03 17:36:56

1

你實際上是打印出4個非打印字符在您的for循環。

字符串中可打印字符的總數爲50.您的長度變量爲51,因爲您爲其添加1。然後for循環從0到51 + 2,這將打印總共54個字符。

但是,由於您的Appendstring函數錯誤地按照John描述的方式嵌入了空字節,因此字符串中有4個空字符。當您將空字符流到cout時,它是不可打印的,並且不顯示任何內容。

一旦你改變Appendstring功能約翰介紹,那麼你就不需要加1,長度和for循環應該是

for (int i=0; i<length; i++)